I have read several articles and stackoverflow posts, but I am still a bit stuck with how to make this work.
I have an enum list that I want to bind to a dependency property, which is then bound to a combobox. When I load the program, the combobox is empty.
Once this is working, I want to display the name in the box (i.e. accessory) and the hex as the value.
XAML:
<ComboBox ItemsSource="{Binding BodyTypeFlags}" />
C#:
public enum BodyTypeFlagsTS4
{
Accessory = 0x0000000A,
Blush = 0x00000020
}
public BodyTypeFlagsTS4 BodyTypeFlags
{
get { return (BodyTypeFlagsTS4)GetValue(BodyTypeFlagsProperty); }
set { SetValue(BodyTypeFlagsProperty, value); }
}
public static readonly DependencyProperty BodyTypeFlagsProperty =
DependencyProperty.Register("BodyTypeFlags", typeof(BodyTypeFlagsTS4),
typeof(MainWindow), new PropertyMetadata(default(BodyTypeFlagsTS4)));
Edit: I have done as suggested and I can now see the list of enum items in the combo box. I have two problems:
If I remove the = hex part (so, it just has Accessory and Blush) then the test button will come back with Accessory - every time. Even when I have blush selected. (I don't want to change the enum format, but this tells me that the two way binding isn't working.)
public BodyTypeFlagsTS4 BodyTypes
{
get { return (BodyTypeFlagsTS4)GetValue(BodyTypesProperty); }
set { SetValue(BodyTypesProperty, value); }
}
public static readonly DependencyProperty BodyTypesProperty =
DependencyProperty.Register("BodyTypes", typeof(BodyTypeFlagsTS4), typeof(MainWindow), new PropertyMetadata());
private void Button_Click(object sender, RoutedEventArgs e)
{
Dispatcher.BeginInvoke(new Action(() =>
{
System.Windows.MessageBox.Show(System.Enum.GetName(typeof(BodyTypeFlagsTS4), this.BodyTypes));
}));
}
You need to provide a list of available values for the ComboBox
. For example:
public BodyTypeFlagsTS4[] AvailableBodyTypeFlags
{
get { return (BodyTypeFlagsTS4[])Enum.GetValues(typeof(BodyTypeFlagsTS4)); }
}
Then bind your ComboBox
to the list:
<ComboBox ItemsSource="{Binding AvailableBodyTypeFlags}"
SelectedItem="{Binding BodyTypeFlags}" />
And you don't actually need dependency properties. Implementing INotifyPropertyChanged
in your view-model is enough.
Try this solution: Zip with solution
In general you must wrap your enum with object. Look the commented out code to see how to retrieve enum's names.
The part of the XAML code:
<Grid.Resources>
<ObjectDataProvider x:Key="tools"
MethodName="GetValues"
ObjectType="{x:Type sys:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="local:Tool" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Grid.Resources>
<ComboBox x:Name="cmbTools"
ItemsSource="{Binding Source={StaticResource tools}}"
SelectedItem="{Binding Path=ToolType, Mode=TwoWay}" />
User contributions licensed under CC BY-SA 3.0