In a Silverlight Web app, I have a service and its interface in where I declared an Enum with the days of the week:
[Serializable]
[DataContract]
[Flags]
public enum WeekDaysFlags : int {
[EnumMember]
Monday = 1,
[EnumMember]
Tuesday = 2,
[EnumMember]
Wednesday = 4,
[EnumMember]
Thursday = 8,
etc.
Back in the application, I have a checkbox for each day that I would like to bind; I did make a pretty converter that accepts a parameter:
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
int d;
if (int.TryParse(parameter.ToString(), out d))
{
WeekDaysFlags mask = WeekDaysFlags.Monday;
switch (d)
{
case 0:
mask = WeekDaysFlags.Sunday;
break;
case 1:
mask = WeekDaysFlags.Monday;
break;
case 2:
mask = WeekDaysFlags.Tuesday;
break;
case 3:
mask = WeekDaysFlags.Wednesday;
break;
case 4:
mask = WeekDaysFlags.Thursday;
break;
case 5:
mask = WeekDaysFlags.Friday;
break;
case 6:
mask = WeekDaysFlags.Saturday;
break;
}
WeekDaysFlags day = (WeekDaysFlags)value;
return (day & mask) == day;
}
return false;
}
Then the IsChecked property of the checkboxes receives something like below, with parameters from 0 to 6 for each day.
IsChecked="{Binding WeeksDays, Mode=TwoWay, Converter={StaticResource DayOfWeekConverter}, ConverterParameter=1}"
Then I run my program, read the database, bind the object aaaaand… nothing! I expect to have monday and wednesday checked since the WeekDays variable contains 5.
When I debug, I do step into the converter with right value and the right parameter, it does return true or false when it is supposed to do so, but in the UI, none of the checkbox is checked. No comprendo…
For the moment, since I need it to work, I assign IsChecked manually from the code behind…
If you have a solution, that would be great! Also I wonder how the binding will work when I will need to “read” the checked checkboxes; i.e. how to get ‘Monday | Wednesday | Thursday’, or 13, or whatever in my binded variable from the checkboxes /me scratch head
Thank you for your help 😉
Sylvain
The whole bitmask-converter setup strikes me as over-engineering. It will be difficult to get right and it is not very flexible.
Consider unpacking your enum into an array of booleans on your ViewModel. Make it a List of (bool, string) and you can bind it to an ItemsControl with a CheckBox template. No more repeated code and markup.