0

我有一个组合框并绑定 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 中设置。

4

1 回答 1

4

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

OrganizationalPost = OrganizationalPostCollection[selectedItemIndex];

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

OrganizationalPost = OrganizationalPostCollection.Where(p => p.Id == itemToSelect.Id).
Single();
于 2013-08-20T08:14:45.177 回答