【问题标题】:wpf programatically set combobox selected item when bound to dictionary绑定到字典时,wpf 以编程方式设置组合框选定项
【发布时间】:2012-10-12 13:27:15
【问题描述】:

我有一个绑定做字典的组合框

Dictionary<String, myClass> boxItems;

组合框有以下数据模板:

<DataTemplate>
    <TextBlock Text="{Binding Path=Key}"></TextBlock>
</DataTemplate>

这适用于加载值和获取选定的值,但是我不知道如何从代码隐藏中设置选定的值。

任何指针?

我尝试将 selectedItem 和 selectedValue 设置为一个键(我知道它在字典中),但是当我加载页面时,组合框没有选择任何内容。

【问题讨论】:

    标签: c# wpf dictionary combobox


    【解决方案1】:

    将此添加到您的组合框

    <ComboBox SelectedItem="{Binding SelectedBoxItem}"/>
    

    并在实现 INotifyPropertyChanged 的​​类中使用它:

    private myClass _selectedBoxItem;
    public myClass SelectedBoxItem
    {
        get { return _selectedBoxItem; }
        set
        {
            _selectedBoxItem = value;
            OnPropertyChanged("SelectedBoxItem");
        }
    }
    

    【讨论】:

      【解决方案2】:

      您需要使用要选择的键创建一个 KeyValuePair。

      你可以这样做:

       myCombo.SelectedItem = new KeyValuePair<string, int>("myKey", boxItems["myKey"]);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-09-18
        • 2011-02-01
        • 1970-01-01
        • 2014-04-18
        • 2012-06-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多