我會用轉換器這一點。以底層對象和屬性名稱作爲參數發送它。返回鍵/值陣列,這樣就可以結合這兩個值(索引/枚舉值),並顯示文本:
<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進行子類化或創建應用相關屬性的行爲。
謝謝。需要一些時間來檢查這一點。 – gawicks