0

我已将DisplayMemberPathComboBox绑定DataView到某些字符串属性:

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

我的虚拟机看起来像这样:

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();
        }
4

1 回答 1

0

所以你试图将SomeProperty价值转化为ContentControl.Content? 尝试这个:

StackOverflow WPF 组合框 DisplayMemberPath

您将无法两次设置相同的属性,这似乎是您正在做的事情。基本上,从以下位置删除DisplayMemberPath

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

并设置

<ComboBox.ItemTemplate>
    <DataTemplate >
        <StackPanel Orientation="Horizontal">
            <Rectangle Width="5" Height="5" Fill="Red" />
            <TextBlock Text="{Binding Path=MyColumn}"/>
        </StackPanel>
    </DataTemplate>
</ComboBox.ItemTemplate>
于 2013-06-07T13:10:10.993 回答