![](/img/trans.png)
[英]C# .net Combobox displays valuemember not displaymember when bound to dataset
[英]ComboBox with bound DisplayMember and ItemTemplate
我将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();
}
因此,您正在尝试将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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.