【问题标题】:ComboBox binding to referenced (relative) sourceComboBox 绑定到引用(相对)源
【发布时间】: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 设置正确,SelectedItemItems 集合中的第一个 项,但 ComboBox 显示时没有选择。为什么?

【问题讨论】:

    标签: c# wpf combobox binding


    【解决方案1】:

    我将对 Items 使用 ObservableCollection 而不是 List,对 ComboBox 使用 SelectedItem,而不是 SelectedValue。

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

    【讨论】:

    • ObservableCollection 无济于事(列表从未更改,无需通知)。但是SelectedItem 成功了,谢谢。没有注意到我使用了错误的属性来绑定。
    • 不客气。如果对您有帮助,请随时接受答案。干得好。
    【解决方案2】:

    @Giangregorio 的回答很好,而且总体上可以工作,但现在我记得为什么我首先使用SelectedValue

    SelectedValueItemsSource 包含SelectedValue 时很有用。如果使用SelectedItem(根据答案),则绑定将使用null 调用setter,就好像用户可以从列表中选择null。我正在利用这种情况(以避免使用数据模板和更复杂的 ViewModel),所以我必须坚持使用SelectedValue,我想我在其他情况下找到了问题的原因 should-work .

    我必须先声明ItemsSource 绑定,然后再声明SelectedValue

    <ComboBox ItemsSource="{Binding Source.Items}"
          SelectedValue="{Binding Source.SelectedItem}"
          DisplayMemberPath="Name" />
    

    有效!

    听起来像是另一个特定于 xaml 的问题,类似于 declare CommandParameter before Command 问题。

    【讨论】:

    • 在不使用 SelectedValuePath 的情况下使用 SelectedValue 应该与使用 SelectedItem 没有什么不同......但是如果它有效,它就有效!
    • @Giangregorio,是的,但它完全需要这个顺序才能正常工作。在设置SelectedValue 之前设置ItemsSource。如果使用SelectedItem,则顺序无关紧要。哪个……有趣?
    猜你喜欢
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    • 2011-03-08
    • 2013-07-17
    • 2018-09-05
    • 2011-03-07
    • 2018-11-27
    • 2021-08-27
    相关资源
    最近更新 更多