获取键作为Combobox在Dictionary绑定中选择的项目

时间:2014-07-02 14:55:26

标签: c# wpf dictionary combobox

我有一个与Combobox的字典绑定。例如,让我们说字典有如下所示的数据集: -

{1,item1}
{2,item2}

现在,当您选择任何选项时,Combobox.SelectedItem应仅获取整数键而不是值。

以下是代码: -

public static Dictionary<int, string> newDict{ get; set; }
newDict = MTMInteraction.getPlanId();
txtPlanId.ItemsSource = newDict;

XAML代码: -

<ComboBox x:Name="txtPlanId"  ItemsSource="{Binding newDict}"  IsEditable="True"    Margin="-2,0,79,3" Text="Enter  ID"  HorizontalAlignment="Center"  VerticalAlignment="Bottom"/>

2 个答案:

答案 0 :(得分:0)

而不是SelectedItem使用SelectedValuePath / SelectedValue属性。将SelectedValuePath针对ComboBox设置为您要获取的属性,并将SelectedValue绑定到视图模型中的某个属性

<ComboBox 
    x:Name="txtPlanId" 
    ItemsSource="{Binding newDict}" 
    ... 
    SelectedValuePath="Key"
    SelectedValue="{Binding SomeIntProperty}"/>

或代码txtPlanId.SelectedValue应该为Key

提供KeyValuePair<int,string>部分内容

答案 1 :(得分:0)

的DisplayMemberPath = “密钥”

比你问的更多,但确实回答了问题(我认为)

<Window x:Class="BindDictionary.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        DataContext="{Binding RelativeSource={RelativeSource self}}"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ListBox ItemsSource="{Binding Path=DLBS, Mode=OneWay}"
                 DisplayMemberPath="Key"
                 SelectedValuePath="Key" 
                 SelectedValue="{Binding Path=DLBSkey}"/>   
    </Grid>
</Window>

using System.ComponentModel;
namespace BindDictionary
{
    public partial class MainWindow : Window , INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        protected void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
        private byte? dlBSkey = 1;
        private Dictionary<byte, string> dlBS = new Dictionary<byte, string>() { { 1, "one" }, { 2, "two" }, { 5, "five" } };      
        public MainWindow()
        {
            InitializeComponent();
        }
        public Dictionary<byte, string> DLBS { get { return dlBS; } }
        public byte? DLBSkey
        {
            get { return dlBSkey; }
            set
            {
                if (dlBSkey == value) return;
                dlBSkey = value;
                NotifyPropertyChanged("DLBSkey");
            }
        }

    }
}