将属性值数据绑定到组合框

时间:2014-05-19 20:16:20

标签: c# wpf data-binding

我有一组带有一组这样的属性的类;每个都有一个自定义属性,指示它可能采取的可能值。有没有将这些值数据绑定到组合框而不是使用<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 个答案:

答案 0 :(得分: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,或创建应用相关属性的Behavior。