I have a Character Class that has an property Gender that is an Enum. What I want my code to do is to switch images based on what gender my Character is(if the character is male = male image).
Where I am having the problem is how to correctly access and get this Enum value. You see, I am creating an ObservableCollection of type Character. I am then binding this collection to a ComboBox and then displaying the DisplayMemberPath via the ItemTemplate.
I believe I am doing all the binding right, but I am not accessing the Character Gender property correctly in my value converter.
The XAML: Referencing the Converter && ComboBox
xmlns:converters="clr-namespace:ImageViaGenderTest_2014"
Title="MainWindow" Height="350" Width="1004.932">
<Window.Resources>
<converters:GenderToIconFilenameConverter x:Key="IconConverter"/>
</Window.Resources>
<ComboBox x:Name="Character_ComboBox" HorizontalAlignment="Left" VerticalAlignment="Top" Width="328" Height="25">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Width="50" Text="{Binding Name}"/>
<TextBlock Width="50" Text="{Binding Level}"/>
<Image Source="{Binding Gender, Converter={StaticResource IconConverter}}"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
The Observable Collection Setup in MainWindow
public ObservableCollection<Character> squad_members = new ObservableCollection<Character>();
public MainWindow()
{
InitializeComponent();
squad_members.Add(new Character() { Name = "john_snow_knows_nothing", Level = 8, _Gender = Gender.Male});
squad_members.Add(new Character() { Name = "Ygritt_gets_wrecked", Level = 4, _Gender = Gender.Female});
Binding comboBinding = new Binding();
comboBinding.Source = squad_members;
BindingOperations.SetBinding(Character_ComboBox, ComboBox.ItemsSourceProperty, comboBinding);
}
The Custom Value Converter Class(Where I think I'm referencing the Gender Enum incorrectly) ERROR AREA:
[ValueConversion(typeof(Gender), typeof(Image))]
public class GenderToIconFilenameConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
switch ((Gender)value)
{
case Gender.Female:
return "character1.jpg";
case Gender.Male:
return "character2.jpg";
default:
return null;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
Character Class:
public class Character
{
public string Name { get; set; }
public int Level { get; set; }
public Gender _Gender { get; set; }
}
Gender Enum:
public enum Gender
{
Male, Female
}
Am i referencing my Character Gender enum incorrectly? Or is there something else I forgot? I also got help from this question: Bind Icon depending on Enum in WPF Treeview