2017-02-15 92 views
0

你好,我有一个WPF绑定的问题,并想知道我是否试图实现的实际上是可能的。WPF - 组合框的复杂绑定

我有一个与ItemsSource绑定到X509FindType枚举的ComboBox,使用控件中的ObjectDataProvider,如下所示。

<ObjectDataProvider x:Key="x509FindTypes" MethodName="GetValues" ObjectType="{x:Type System:Enum}"> 
    <ObjectDataProvider.MethodParameters> 
     <x:Type TypeName="cryptography:X509FindType" /> 
    </ObjectDataProvider.MethodParameters> 
</ObjectDataProvider> 

的问题是,我需要做一个双向的SelectedItem,在我的模型属性之间的结合是字符串类型(我不能改变它是特定枚举类型)。

目标似乎很简单 - 每当我在模型中设置一个字符串组合框应显示此值。另一方面,用户也可以从ComboBox中选择元素,并将字符串的值更新为该枚举类型的名称。

感谢您的任何建议和对我丑陋的英语感到抱歉。

+0

您应该使用一个转换器的转换之间枚举值和一个字符串:https://www.codeproject.com/Tips/868163/IValueConverter-Example-and-Usage-in-WPF – mm8

回答

2

您应该使用转换器在enum值和string之间进行转换。

请参考以下示例代码。

转换器:

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(); 
    } 
} 

查看:

<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}}" /> 

视图模型:

private string _s = "FindByTimeExpired"; 
public string YourStringProperty 
{ 
    get { return _s; } 
    set { _s = value; } 
} 
+0

工程很好,谢谢你mm8! – Kris82