【问题标题】:Don't set SelectedItem for Combobox in wpf mvvm不要在 wpf mvvm 中为 Combobox 设置 SelectedItem
【发布时间】:2013-08-20 05:15:41
【问题描述】:

我有一个组合框并绑定 ItemsSource 和 SelectedItem

<ComboBox DisplayMemberPath="Name"  ItemsSource="{Binding OrganizationalPostCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"  SelectedItem="{Binding OrganizationalPost,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"  HorizontalAlignment="Left" Width="230" Margin="5" />

在 ViewModel 中

OrganizationalPost _organizationalPost;
public OrganizationalPost OrganizationalPost
{
    get { return _organizationalPost; }
    set
    {
        if (value != _organizationalPost)
        {
            _organizationalPost = value;
            RaisePropertyChanged("OrganizationalPost");
        }
    }
}

ICollectionView _organizationalPostCollection;
public ICollectionView OrganizationalPostCollection
{
    get { return _organizationalPostCollection; }
    set
    {
        if (value != _organizationalPostCollection)
        {
            _organizationalPostCollection = value;
            RaisePropertyChanged("OrganizationalPostCollection");
        }
    }
}

在构造函数中

OrganizationalPostCollection = CollectionViewSource.GetDefaultView(db.OrganizationalPost.ToList());
OrganizationalPost = SelectedUser.OrganizationalPost;

OrganizationalPost 有值,但不要在 SelectedItem 中设置。

【问题讨论】:

  • SelectedUser.OrganizationalPost 的来源是对OrganizationalPostCollection 中的OrganizationalPostitem 的引用还是来自其他地方?
  • 它来自其他地方。
  • 尝试在ICollectionView中设置对象类型(即ICollection
  • 可能的原因之一是所选对象 (SelectedUser.OrganizationalPost) 的哈希 id 与 (OrganizationalPostCollection) 中的任何项目都不匹配。您需要确保所选项目与 ItemsSource 中的项目之一完全匹配
  • @ar.gorgin 这意味着它们是不同的参考,即 SelectedUser.OrganizationalPost 的 id 不同,即不同的参考,即创建但不存在于列表中。列表中有一个类似的项目,即具有相同的 id 和相同的成员,但地址不同

标签: wpf data-binding mvvm combobox


【解决方案1】:

为了选择 SelectedItem 属性的值并更新 UI,您设置的项目必须来自为同一控件设置为 ItemsSource 的集合:

OrganizationalPost = OrganizationalPostCollection[selectedItemIndex];

或者如果您的班级具有唯一可识别的属性:

OrganizationalPost = OrganizationalPostCollection.Where(p => p.Id == itemToSelect.Id).
Single();

【讨论】:

    猜你喜欢
    • 2012-06-19
    • 1970-01-01
    • 2017-02-20
    • 2014-03-18
    • 1970-01-01
    • 2011-02-23
    • 2023-03-09
    • 1970-01-01
    • 2010-10-14
    相关资源
    最近更新 更多