c# - ComboBox 绑定(bind)到引用的(相对)源

标签 c# wpf combobox binding

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 设置正确,SelectedItemItems 集合中的第一个 项目,然而 ComboBox 显示时没有选择。为什么?

最佳答案

我将为项目使用 ObservableCollection 而不是 List,并为 ComboBox 使用 SelectedItem,而不是 SelectedValue。

阅读这个关于 SelectedItem 和 SelectedValue 之间差异的好答案 Difference between SelectedItem, SelectedValue and SelectedValuePath

关于c# - ComboBox 绑定(bind)到引用的(相对)源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33913708/

相关文章:

c# - 将 bool 条件传递给我可以在需要时调用的方法

C# StarTeam SDK

c# - EventAggregator 无法跨模块访问

wpf - 鼠标悬停时更改背景颜色

python - 根据组合框 1 填充组合框 2

c# - EF 无法将 double 转换为单精度

c# - 参数化 Where IN 子句不适用于 CosmosClient QueryDefinition 对象

c# - 打开组合框下拉列表时更改光标

c# - 将简单的 List<myClass> 绑定(bind)到 Combobox

c# - 组合框将 itemsource 绑定(bind)到自定义列表并将 selecteditem 绑定(bind)到该列表的实例不起作用