【发布时间】:2015-11-25 10:13:08
【问题描述】:
将ComboBox 绑定到引用源时:
<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的列表并选择了正确的项目(切换视图时我可以看到它的Name); - 对于多个项目
ComboBox错误:没有选择(但下拉列表在那里并且工作正常),切换视图或更改Source时选择不会持续存在(例如,在 2 个源之间)。
似乎ComboBox 识别SelectedValue 或在ItemsSource 中找到它有些问题。而且我不知道出了什么问题。
调试没有发现任何东西:Items 设置正确,SelectedItem 是Items 集合中的第一个 项,但 ComboBox 显示时没有选择。为什么?
【问题讨论】: