【问题标题】:Key Value Pair Combobox in WPFWPF 中的键值对组合框
【发布时间】:2011-12-15 13:53:18
【问题描述】:

考虑我有绑定到 ComboBox 的键值对集合(Ex Key=MSFT Value=MSFT Microsoft)。 DisplayMemeberPath=值。以下需要完成

  • 在选择项目时,只需在 Combo 中显示 Key,

  • 用户还可以在 Combo 中键入一个全新的值。

我想不出同时支持这两个功能的解决方案。解决一个问题。

<ComboBox IsTextSearchEnabled="True" Name="cmbBrokers" IsEditable="True" 
ItemsSource="{Binding BrokerCodes}" SelectedValuePath="Key" 
 DisplayMemberPath="Value" Text="{Binding SelectedBroker, Mode=TwoWay}">

【问题讨论】:

  • 您可以尝试使用单独的文本框来显示所选项目的键。命名组合框并将其用作绑定元素源,路径为 selecteditem。我认为您使用 selecteditem.key 来获取密钥,但我不确定。
  • 如果您想查看用户输入的新输入,您必须使用新值更新您的 itemssource (BrokerCodes)

标签: c# .net wpf xaml combobox


【解决方案1】:

我猜你要找的内容如下。

public class ComboBoxPairs
{
    public string _Key { get; set; }
    public string _Value { get; set; }

    public ComboBoxPairs(string _key,string _value )
    {
        _Key = _key ;
        _Value = _value ;
    }
}

然后你继续像这样使用这个类

List<ComboBoxPairs> cbp = new List<ComboBoxPairs>();

cbp.Add(new ComboBoxPairs("Microsoft", "MSFT"));
cbp.Add(new ComboBoxPairs("Apple", "AAPL"));

并将其绑定到您拥有的组合框

cmbBrokers.DisplayMemberPath = "_Key";
cmbBrokers.SelectedValuePath = "_Value";

cmbBrokers.ItemsSource = cbp;

当您需要访问它时,只需执行此操作

ComboBoxPairs cbp = (ComboBoxPairs)cmbBrokers.SelectedItem;

string _key = cbp._Key;
string _value = cbp._Value;

这就是你需要做的。

【讨论】:

    【解决方案2】:

    使用更通用的解决方案扩展 Adams 示例。

    在 xaml.cs 中创建一个可观察的集合属性并为其分配一个集合。

    ObservableCollection < KeyValuePair < string , string > > MyCollection { get; set; }
    
    MyCollection = new ObservableCollection < KeyValuePair < string , string > > ( ) 
    
    {
       new KeyValuePair < string , string > ("key1" ,"value1"),
       new KeyValuePair < string , string > ("key2" ,"value2")
    };
    

    在 xaml 文件数据中,将您的 observable 集合绑定到您在后面的代码中创建的属性。

    <ComboBox Grid.Row="3"
              Grid.Column="1"
              ItemsSource="{Binding MyCollection}"
              DisplayMemberPath="Key" />
    

    如果您希望改为显示值,可以将 DisplayMemberPath="Key" 更改为 DisplayMemberPath="Value"

    【讨论】:

      【解决方案3】:

      我不认为直接开箱即用的组合框是适合您在这种情况下使用的 UI 元素。这里的问题是组合框并非旨在支持键/值对,特别是如果您希望用户能够在绑定到键时向字典添加值。例如,如果您允许他们添加值,他们如何添加键或选择要更新的键?

      我认为解决方案是有两个控件:一个用于键选择的组合框和一个用于值输入的文本框。在用户选择一个键之前,值文本框是隐藏的。选择键后,让他们在文本框中输入值输入,然后按 enter 或按钮,然后将值设置为所选键。

      【讨论】:

        猜你喜欢
        • 2012-05-28
        • 1970-01-01
        • 2012-08-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多