nerdalert nerdalert - 2 months ago 12
C# Question

C# WPF set bound checkbox to checked by default

I have a checkbox with it's

IsChecked
property bound already.

<CheckBox
x:Name="sortChk"
Content="Sort Variables"
HorizontalAlignment="Right"
Margin="10,10,10,5"
IsChecked="{Binding SortVariables}"
/>


I need it to be checked by default on form load. I've seen that having the
IsChecked
property set to
true
will achieve this, but I will lose the binding then.

How do I do this? I'm very new to WPF so forgive me if it's an easy solution.

Edit: I have figured out why the below code was not working on form load, and it's because I did not have it in the Default constructor. Moving it there does the trick. I had a feeling it was something trivial (and stupid on my part). Thanks for the help!

DataCompareVM dcvm = new DataCompareVM(dataset1FullPath, dataset2FullPath);
dcvm.SortVariables = true;
DataContext = dcvm;

Answer Source

You need to set the SortVariables on your DataContext.

In your xaml.cs file, look for code that looks like:

this.DataContext = something;

and change it to:

something.SortVariables = true;
this.DataContext = something;