DataGridComboBoxColumn绑定转换器无法按预期工作

时间:2016-06-15 08:19:08

标签: c# .net wpf xaml mvvm

参考我的其他question

我有这个DataGridComboBoxColumn:

<DataGridComboBoxColumn Header="Master" SelectedItemBinding="{Binding MasterId}" SelectedValueBinding="{Binding Id}" DisplayMemberPath="Id" ItemsSource="{Binding Data.Masters, Converter={converters:SimpleComboItemConverter}, Source={StaticResource proxy}}" />

我为尝试将值保存到行时引发的运行时错误创建了此IValueConverter。

[ValueConversion(typeof(string), typeof(SimpleComboItem<>))]
public class SimpleComboItemConverter : MarkupExtension, IValueConverter
{
    public static SimpleComboItemConverter converter;

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

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

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        if (null == converter)
        {
            converter = new SimpleComboItemConverter();
        }
        return converter;
    }
}

但在调试内部时,Convert方法的值为IEnumerable对象而不是stringSimpleComboBoxItem<>

SimpleComboBoxItem类非常简单,列中的ComboBox显示正确的值:

public class SimpleComboItem<T>
{
    public T Value { get; set; }
    public string Text { get; set; }
}

我做错了什么?

1 个答案:

答案 0 :(得分:1)

问题在于xaml,您将Id映射为项目。您必须使用SelectedValueBinding而不是SelectedItemBinding。