两个具有相同CollectionViewSource ItemSource的组合框相互更新

gri*_*ner 9 data-binding wpf xaml collectionviewsource

在我的ViewModel上,我有2个属性(都实现了属性更改通知):

CountryOfIssue
Nationality
Run Code Online (Sandbox Code Playgroud)

在我的View上,我有一个指向我的Entity Framework上下文的本地实例的CollectionViewSource:

<CollectionViewSource x:Key="cvsCountries" Source="{Binding LocalContext.Countries}" CollectionViewType="{x:Type ListCollectionView}">
    <CollectionViewSource.SortDescriptions>
        <scm:SortDescription PropertyName="Name" />
    </CollectionViewSource.SortDescriptions>
</CollectionViewSource>
Run Code Online (Sandbox Code Playgroud)

同样在这个页面上,我有两个组合框用于设置CountryOfIssue和国籍的值:

<ComboBox IsEnabled="{Binding CanEditCountryOfIssue}" ItemsSource="{Binding Source={StaticResource cvsCountries}}" DisplayMemberPath="Name" SelectedValuePath="Id" SelectedItem="{Binding CountryOfIssue, Mode=TwoWay, UpdateSourceTrigger=LostFocus, ValidatesOnDataErrors=True}" />

<ComboBox IsEnabled="{Binding CanEditNationality}" ItemsSource="{Binding Source={StaticResource cvsCountries}}" DisplayMemberPath="Name" SelectedValuePath="Id" SelectedItem="{Binding Nationality, Mode=TwoWay, UpdateSourceTrigger=LostFocus, ValidatesOnDataErrors=True}" />
Run Code Online (Sandbox Code Playgroud)

通过这种设置,每当我改变其中一个组合框的值时,另一个也会改变...这是预期的行为吗?

(我已经使用另一个CollectionViewSource实现了修复,我只是想知道这是否正常)

H.B*_*.B. 12

这是正常的,CollectionViews有一个CurrentItem,如果它ItemsSource是一个CollectionView他们得到同步,请参阅IsSynchronizedWithCurrentItem:

如果SelectedItem始终与ItemCollection中的当前项同步,则返回true;否则返回true.如果SelectedItem从未与当前项同步,则返回false;否则返回false.如果SelectedItem仅在Selector使用CollectionView时与当前项同步,则返回null.默认值为null.

因此,您可以通过将该属性设置为手动将其关闭false.

(顺便说一下,你也可以绑定到CurrentItemCollectionView通过斜线.例如,People/Name结合到Name目前的人的财产People.)