问题描述
我有一个关于绑定我的 displayMember
的 ComboBox
的快速问题。
例如,我有一个带有 keyvaluePair
的列表:
1,值1;
2、Value2;
3、Value3;
我的 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
不可编辑,您可以为您的键值对创建一个 DataTemplate
。
<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}"/>
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,CultureInfo culture)
{
throw new NotImplementedException("One way converter.");
}
}