I have bound a flagged enum to a bunch of checkboxes by using a value converter that works as described in the solution to this question. This works fine when I'm working with a flag that hasn't been set to anything.
However, in the non-trivial use case that the flag is actually set to some data, on load the checkboxes are bound correctly to the enum field. However, when I check/uncheck the box, it seems this binding has been lost.
For example, my enum and value converters are as follows:
[Flags]
enum Fruits : int { Apple = 1, Orange = 2, Peach = 4, None = 0 };
public Converter : IValueConverter
{
private Fruits target;
public Converter() { }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Fruits mask = (Fruits)parameter;
this.target = (Fruits)value;
return ((mask & this.target) != 0);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
this.target ^= (Fruits)parameter;
return this.target;
}
}
My XAML (in a datagrid) is as follows:
<toolkit:DataGrid.Columns>
<toolkit:DataGridTemplateColumn Header="Fruits">
<toolkit:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<DataTemplate.Resources>
<ui:Converter x:Key="Converter" />
</DataTemplate.Resources>
<StackPanel>
<CheckBox Content="Apple" IsChecked="{Binding Path=Fruits, Converter={StaticResource Converter}, ConverterParameter={x:Static constants:Fruits.Apple}}" />
<CheckBox Content="Orange" IsChecked="{Binding Path=Fruits, Converter={StaticResource Converter}, ConverterParameter={x:Static constants:Fruits.Orange}}" />
<CheckBox Content="Peach" IsChecked="{Binding Path=Fruits, Converter={StaticResource Converter}, ConverterParameter={x:Static constants:Fruits.Peach}}" />
</StackPanel>
</DataTemplate>
</toolkit:DataGridTemplateColumn.CellTemplate>
</toolkit:DataGridTemplateColumn>
</toolkit:DataGrid.Columns>
When I load the binding from the object, it goes through Convert for each item in the list (an ObservableCollection) and binds the checkboxes correctly, and stores them in the target field. However, when I check/uncheck another box, the target field is defaulted to "None" and the behavior is as if you're starting over from scratch.
Any help?