Reputation: 42215
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?
Upvotes: 0
Views: 644
Reputation: 3738
EDIT: This isn't an asnwer to the OP's question, but I feel it deserves mentioning.
It appears that you're checking for enum flags, the proper boolean expression is:
(options.Options.Arming & arming) == arming
if this expression returns true
, then options.Options.Arming
contains the flag stored in arming
It is also important that your enum Arming
members be defined correctly!
Upvotes: -1
Reputation: 20471
In calling you CheckBox
constructor you set IsChecked
, which sets the IsCheckedProperty
on the checkbox. You then set the IsCheckedProperty
again with a Binding
, so the first setting is overridden.
I suspect your issue is with the Converter
and the ConverterParameter
in the Binding
Upvotes: 2