I’m generating CheckBoxes dynamically and I want to check them depending on which options should be selected.
I have the following XAML:
<StackPanel>
<StackPanel x:Name="ArmingPanel" />
</StackPanel>
And the following code:
private void AddCheckBoxes(OptionsVM options)
{
var converter = new FlagsEnumValueConverter();
foreach (Arming arming in Enum.GetValues(typeof(Arming)))
{
if (arming != Arming.None)
{
var binding = new Binding()
{
Path = new PropertyPath("Arming"),
Converter = converter,
ConverterParameter = arming
};
var checkBox = new CheckBox()
{
Content = arming.ToString(),
IsChecked = (options.Options.Arming & arming) != Arming.None
};
checkBox.SetBinding(CheckBox.IsCheckedProperty, binding);
ArmingPanel.Children.Add(checkBox);
}
}
}
Depending on which flags have been set, the following should be set to true or false:
IsChecked = (options.Options.Arming & arming) != Arming.None
I can see this value being set correctly when I debug, but when the checkboxes are listed on the screen they’re always unchecked.
How can I get them to be checked as expected?
In calling you
CheckBoxconstructor you setIsChecked, which sets theIsCheckedPropertyon the checkbox. You then set theIsCheckedPropertyagain with aBinding, so the first setting is overridden.I suspect your issue is with the
Converterand theConverterParameterin the Binding