微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ComboBox KeyValuePair 绑定 WPF - 显示成员

如何解决ComboBox KeyValuePair 绑定 WPF - 显示成员

我有一个关于绑定我的 displayMemberComboBox快速问题。 例如,我有一个带有 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.");
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。