将 ComboBox
绑定(bind)到引用源时:
<ComboBox SelectedValue="{Binding Source.SelectedItem}"
ItemsSource="{Binding Source.Items}"
DisplayMemberPath="Name" />
Source
在哪里
SourceType _source;
public SourceType Source
{
get { return _source; }
set { _source = value; OnPropertyChanged(); }
}
和SourceType
是
public class SourceType: INotifyPropertyChanged
{
Item _selectedItem;
public Item SelectedItem
{
get { return _selectedItem; }
set { _selectedItem = value; OnPropertyChanged(); }
}
public IReadOnlyList<Item> Items { get; }
public SourceType(...)
{
Items = new List<Items>(...) // **new** list generated from passed arguments
SelectedItem = Items.First();
}
}
Item
是
public class Item: INotifyPropertyChanged
{
string _name;
public string Name
{
get { return _name; }
set { _name = value; OnPropertyChanged(); }
}
}
发生以下情况:
- 只有一个来源(如果
Source
永远不会改变)它工作:ComboBox
显示Items
列表并选择正确的项目(我可以切换 View 时看到它的名称
); - 对于多个项目
ComboBox
错误:没有选择(但下拉列表存在并且工作正常),切换 View 或Source
时选择不会保留> 已更改(例如在 2 个来源之间)。
似乎 ComboBox
在识别 SelectedValue
或在 ItemsSource
中找到它时遇到一些问题。我不知道哪里出了问题。
调试不会发现任何东西:Items
设置正确,SelectedItem
是 Items
集合中的第一个 项目,然而 ComboBox
显示时没有选择。为什么?
最佳答案
我将为项目使用 ObservableCollection 而不是 List,并为 ComboBox 使用 SelectedItem,而不是 SelectedValue。
阅读这个关于 SelectedItem 和 SelectedValue 之间差异的好答案 Difference between SelectedItem, SelectedValue and SelectedValuePath
关于c# - ComboBox 绑定(bind)到引用的(相对)源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33913708/