ObservableDictionary 是一个字典集合,其中的项在被添加、删除或修改时会触发 INotifyCollectionChanged
事件,这使得它可以与 WPF 或 UWP 中的数据绑定机制很好地协同工作。ComboBox 是一种常用的用户界面控件,允许用户从预定义的选项列表中选择一个值。
ObservableDictionary<TKey, TValue>
。以下是一个简单的示例,展示了如何将 ComboBox 绑定到 ObservableDictionary 并获取选定的值:
using System.Collections.ObjectModel;
using System.ComponentModel;
public class ViewModel : INotifyPropertyChanged
{
private ObservableCollection<KeyValuePair<string, string>> _items;
public ObservableCollection<KeyValuePair<string, string>> Items
{
get => _items;
set
{
_items = value;
OnPropertyChanged(nameof(Items));
}
}
private KeyValuePair<string, string> _selectedItem;
public KeyValuePair<string, string> SelectedItem
{
get => _selectedItem;
set
{
_selectedItem = value;
OnPropertyChanged(nameof(SelectedItem));
}
}
public ViewModel()
{
Items = new ObservableCollection<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("1", "Option 1"),
new KeyValuePair<string, string>("2", "Option 2"),
new KeyValuePair<string, string>("3", "Option 3")
};
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
在 XAML 中:
<ComboBox ItemsSource="{Binding Items}"
SelectedItem="{Binding SelectedItem, Mode=TwoWay}"
DisplayMemberPath="Value"
SelectedValuePath="Key"/>
要获取 ComboBox 中选定的字段,可以直接访问绑定的 SelectedItem
属性。例如:
string selectedKey = viewModel.SelectedItem.Key;
string selectedValue = viewModel.SelectedItem.Value;
问题:ComboBox 的选定值没有更新。
原因:可能是由于数据绑定的 Mode
没有设置为 TwoWay
,或者 ViewModel 中的 SelectedItem
属性没有正确实现 INotifyPropertyChanged
接口。
解决方法:
SelectedItem
绑定设置了 Mode=TwoWay
。SelectedItem
属性在值变化时触发 PropertyChanged
事件。通过以上步骤,可以确保 ComboBox 的选定值能够正确地反映在绑定的数据源中,并且可以从 ViewModel 中获取到这些值。
领取专属 10元无门槛券
手把手带您无忧上云