2014-05-19 53 views
1

我有一組類,具有一組像這樣的屬性;每個都有一個自定義屬性,用於指示可能的值。無論如何都要使用<ComboBoxItem/>將這些值數據綁定到組合框而不是硬編碼?將屬性值數據綁定到組合框

[Values("Cash","Bank","Not Applicable")] 
public Nullable<int> PaymentMethod{ get; set; } 

編輯:我的屬性看起來像這樣

class ValuesAttribute:Attribute 
{ 
    public List<string> values { get; set; } 
    public ValuesAttribute(params String[] values) 
    { 
     this.values= new List<string>(); 
     foreach (var v in values) 
     { 
      this.values.Add(v); 
     } 
    } 
} 

回答

1

我會用轉換器這一點。以底層對象和屬性名稱作爲參數發送它。返回鍵/值陣列,這樣就可以結合這兩個值(索引/枚舉值),並顯示文本:

<ComboBox ItemsSource="{Binding ConverterParameter='PaymentMethod',Converter={StaticResource AttributeConverter}}" 
      DisplayMemberPath="Value" SelectedValuePath="Key" 
/> 

轉換器然後可以使用反射得到的值:

public class AttributeConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     if (value != null && parameter as string != null) 
     { 
      var property = value.GetType().GetProperty((string)parameter); 
      if (property != null) 
      { 
       var attribute = property.GetCustomAttributes(typeof(ValuesAttribute), false).OfType<ValuesAttribute>().FirstOrDefault(); 
       if (attribute != null) 
        return attribute.values.Select((display, index) => 
         new KeyValuePair<int, string>(index, display) 
         ).ToArray(); 
      } 
     } 
     return DependencyProperty.UnsetValue; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 

注:如果您需要在應用程序中執行此操作,則可能需要對ComboBox進行子類化或創建應用相關屬性的行爲。

+0

謝謝。需要一些時間來檢查這一點。 – gawicks