带有绑定DisplayMember和ItemTemplate的ComboBox

时间:2013-06-07 12:48:12

标签: c# wpf

我将ComboBox绑定到DataView并将DisplayMemberPath绑定到某个字符串属性:

<ComboBox  DisplayMemberPath="{Binding SomeProperty}" ItemsSource="{Binding MyView}" />

我的VM看起来像这样:

public class MyViewModel
{
    DataTable dt = new DataTable();
    public MyViewModel()
    {
        dt.Columns.Add("MyColumn");
        dt.Rows.Add("AAA");
        dt.Rows.Add("BBB");
    }

    public DataView MyView
    {
        get { return dt.DefaultView; }
    }

    public string SomeProperty
    {
        get { return "MyColumn"; }
    }
}

现在我想自定义ItemTemplate

    <ComboBox.ItemTemplate>
        <DataTemplate >
            <StackPanel Orientation="Horizontal">
                <Rectangle Width="5" Height="5" Fill="Red" />
                <ContentControl Content="{Binding Path=???}" />
            </StackPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>

由于DisplayMemberPath是动态的(我不能将它与ItemTemplate一起使用),我该如何指定路径?

编辑:

到目前为止,这是我的解决方案,但我认为这太复杂了:

<ContentControl.Content>
    <MultiBinding Converter="{StaticResource someMultiConverter}">
        <Binding Path="DataContext.SomeProperty" ElementName="comboBox1" />
        <Binding />
    </MultiBinding>
</ContentControl.Content>

转换器:

public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            //throw new NotImplementedException();
            string path = values[0] as string;
            DataRowView drv = values[1] as DataRowView;
            return drv[path].ToString();
        }

1 个答案:

答案 0 :(得分:0)

您是否尝试将SomeProperty值转换为ContentControl.Content?试试这个:

StackOverflow WPF Combobox DisplayMemberPath

您将无法两次设置相同的属性,这似乎就是您正在做的事情。基本上,请从{<1}}中删除:

DisplayMemberPath

并设置

<ComboBox  DisplayMemberPath="{Binding SomeProperty}"....