We have a Person who can have several Skills (Strength, Intelligence and Luck). In our WPF-Application, we want to bind these Skills to Checkboxes. When a Person has these Skills in his list, then the Checkboxes should be checked:
The Person Class and Enum:
public class Person
{
public string Name { get; set; }
public List<SkillsEnum> Skills { get; set; } // <-- The skills of the user
}
public enum SkillsEnum // <-- All available skills
{
Strength,
Intelligence,
Luck
}
Our View Model:
public class InitAppViewModel : ViewModelBase
{
public Person CurrentPerson { get; set; }
public IEnumerable<string> AvailableSkills
{
get { return Enum.GetNames(typeof(SkillsEnum)).ToList(); }
}
public InitAppViewModel()
{
CurrentPerson = new Person() { Name = "Foo", Skills = new List<SkillsEnum> { SkillsEnum.Luck, SkillsEnum.Intelligence } };
}
}
The respective XAML-Markup:
<ItemsControl x:Name="CurrentPerson_Skills" ItemsSource="{Binding AvailableSkills}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding}" IsChecked="{Binding RelativeSource={RelativeSource AncestorType=ItemsControl}, Path=DataContext.CurrentPerson.Skills, Converter={StaticResource SkillToBoolConverter}}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
The Converter:
public class SkillToBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
// conversion code here which returns a boolean
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
How can we pass the Enum-Value of the Checkbox-Elements and the Skills of the Person into the SkillToBoolConverter so we can validate the skills and return true/false so that the checkboxes are checked/unchecked?