组合框KeyValuePair绑定WPF-显示成员
我得到了一个关于绑定我的组合框KeyValuePair绑定WPF-显示成员,wpf,combobox,binding,keyvaluepair,Wpf,Combobox,Binding,Keyvaluepair,我得到了一个关于绑定我的组合框的DisplayMember的快速问题。 我有一个带有KeyValuePair的列表,例如: 1、价值1 2、价值2 3、价值3 我的SelectedValuePath设置为Key,在我的示例“1”中。 现在我想让我的DisplayMemberPath显示“Key-Value”,例如,文本框应该显示“1-Value1”。 可能吗? 谢谢,这是事先准备好的 例如,您可以这样做: <ComboBox x:Name="cmb1" ItemsSou
组合框的DisplayMember
的快速问题。
我有一个带有KeyValuePair
的列表,例如:
1、价值1
2、价值2
3、价值3
我的SelectedValuePath
设置为Key
,在我的示例“1”中。
现在我想让我的DisplayMemberPath
显示“Key
-Value
”,例如,文本框应该显示“1-Value1”。
可能吗?
谢谢,这是事先准备好的 例如,您可以这样做:
<ComboBox x:Name="cmb1" ItemsSource="{Binding YourDictionary}" SelectedValuePath="Key">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Key}"/>
<TextBlock Text="-"/>
<TextBlock Text="{Binding Value}"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<TextBox Text="{Binding SelectedValue, ElementName=cmb1}"/>
如果您的组合框不可编辑,您可以为键值对创建数据模板
<ComboBox ...>
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock>
<Run Text="{Binding Key, Mode=OneWay}"/>
<Run Text=" - "/>
<Run Text="{Binding Value, Mode=OneWay}"/>
</TextBlock>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
您还可以使用值转换器:
<ComboBox x:Name="cmb1" ItemsSource="{Binding YourDictionary}" SelectedValuePath="Key">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource YourConverter}}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<TextBox Text="{Binding SelectedValue, ElementName=cmb1}"/>
公共类KeyValueConverter:IValueConverter
{
公共对象转换(对象值、类型targetType、对象参数、CultureInfo区域性)
{
if(value为KeyValuePair obj)//在此处使用您的类型
{
返回obj.Key.ToString()+“-”+obj.Value.ToString();
}
返回值;
}
公共对象转换回(对象值、类型targetTypes、对象参数、CultureInfo区域性)
{
抛出新的NotImplementedException(“单向转换器”);
}
}
这个组合框是否应该是可编辑的,例如IsEditable=“True”
?您尝试过吗?文本框不可编辑。我现在将尝试解决方案:)谢谢你,工作完美!
public class KeyValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is KeyValuePair<int, object> obj)//use your types here
{
return obj.Key.ToString() + "-" + obj.Value.ToString();
}
return value;
}
public object ConvertBack(object value, Type targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException("One way converter.");
}
}