[英]wpf programatically set combobox selected item when bound to dictionary
我有一个组合框,该组合框必做字典
Dictionary<String, myClass> boxItems;
组合框具有以下dataTemplate:
<DataTemplate>
<TextBlock Text="{Binding Path=Key}"></TextBlock>
</DataTemplate>
这对于加载值和获取所选值的效果很好,但是我无法从代码隐藏中弄清楚如何设置所选值。
有指针吗?
我尝试将selectedItem和selectedValue设置为Key(我知道它在字典中),但是在加载页面时,组合框没有选择任何内容。
将此添加到您的组合框
<ComboBox SelectedItem="{Binding SelectedBoxItem}"/>
并在实现INotifyPropertyChanged的类中使用此方法:
private myClass _selectedBoxItem;
public myClass SelectedBoxItem
{
get { return _selectedBoxItem; }
set
{
_selectedBoxItem = value;
OnPropertyChanged("SelectedBoxItem");
}
}
您需要使用要选择的密钥创建一个KeyValuePair。
您可以执行以下操作:
myCombo.SelectedItem = new KeyValuePair<string, int>("myKey", boxItems["myKey"]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.