Reputation: 113
Hello I am having a problem with WPF binding and wondering if what I am trying to achieve is actually possible.
I have a ComboBox with ItemsSource bound to X509FindType Enum using the ObjectDataProvider within a control as seen below.
<ObjectDataProvider x:Key="x509FindTypes" MethodName="GetValues" ObjectType="{x:Type System:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="cryptography:X509FindType" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
The problem is that I need to make a two-way binding between SelectedItem and property in my model which is type of string (I can't change it to be that specific Enum type).
The goal seems to be simple - Whenever I set a string in Model the ComboBox should show this value. On the other hand user can also choose the element from ComboBox and the value of the string should be updated to name of that enum type.
Thanks for any advises and sorry for my ugly English.
Upvotes: 0
Views: 250
Reputation: 169200
You should use a converter to convert between the enum
value and a string
.
Please refer to the following sample code.
Converter:
public class EnumToStringConv : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return value;
return (X509FindType)Enum.Parse(typeof(X509FindType), value.ToString(), true);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return ((X509FindType)value).ToString();
}
}
View:
<ObjectDataProvider x:Key="x509FindTypes" MethodName="GetValues" ObjectType="{x:Type System:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="cryptography:X509FindType" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
<local:EnumToStringConv x:Key="EnumToStringConv" />
...
<ComboBox SelectedItem="{Binding YourStringProperty, Converter={StaticResource EnumToStringConv}}"
ItemsSource="{Binding Source={StaticResource x509FindTypes}}" />
View Model:
private string _s = "FindByTimeExpired";
public string YourStringProperty
{
get { return _s; }
set { _s = value; }
}
Upvotes: 2