【问题标题】:ComboBox KeyValuePair Binding WPF - Display MemberComboBox KeyValuePair 绑定 WPF - 显示成员
【发布时间】:2023-03-02 23:47:01
【问题描述】:

我有一个关于绑定我的ComboBoxDisplayMember 的快速问题。 我有一个带有KeyValuePair 的列表,例如:

1,价值1;
2、价值2;
3、价值3;

我的SelectedValuePath 设置为Key,在我的示例中为“1”。 现在我希望我的DisplayMemberPath 显示“Key - Value”,例如文本框应该显示“1 - Value1”。 那可能吗? 提前致谢!

【问题讨论】:

  • 这个ComboBox 是否应该是可编辑的,例如IsEditable="True"?
  • 你试过了吗?
  • 文本框不可编辑。我现在将尝试解决方案:)

标签: wpf combobox binding keyvaluepair


【解决方案1】:

你可以这样做:

<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}"/>

【讨论】:

    【解决方案2】:

    如果您的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>
    

    【讨论】:

      【解决方案3】:

      另一种方法是使用值转换器:

      <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, object parameter, CultureInfo culture)
          {
              throw new NotImplementedException("One way converter.");
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2019-10-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-31
        • 1970-01-01
        • 2016-03-15
        • 2011-11-01
        • 2015-04-07
        相关资源
        最近更新 更多