【发布时间】:2011-09-12 10:23:29
【问题描述】:
假设我们有一个简单的 VM 类
public class PersonViewModel : Observable
{
private Person m_Person= new Person("Mike", "Smith");
private readonly ObservableCollection<Person> m_AvailablePersons =
new ObservableCollection<Person>( new List<Person> {
new Person("Mike", "Smith"),
new Person("Jake", "Jackson"),
});
public ObservableCollection<Person> AvailablePersons
{
get { return m_AvailablePersons; }
}
public Person CurrentPerson
{
get { return m_Person; }
set
{
m_Person = value;
NotifyPropertyChanged("CurrentPerson");
}
}
}
像这样成功地将数据绑定到 ComboBox 就足够了:
<ComboBox ItemsSource="{Binding AvailablePersons}"
SelectedValue="{Binding Path=CurrentPerson, Mode=TwoWay}" />
请注意,Person 已重载 Equals,当我在 ViewModel 中设置 CurrentPerson 值时,它会导致组合框当前项显示新值。
现在假设我想使用CollectionViewSource向我的视图添加排序功能
<UserControl.Resources>
<CollectionViewSource x:Key="PersonsViewSource" Source="{Binding AvailablePersons}">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="Surname" Direction="Ascending" />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
</UserControl.Resources>
现在组合框项目源绑定将如下所示:
<ComboBox ItemsSource="{Binding Source={StaticResource PersonsViewSource}}"
SelectedValue="{Binding Path=CurrentPerson, Mode=TwoWay}" />
它确实会被排序(如果我们添加更多项目,它会清晰可见)。
但是,当我们现在在 VM 中更改 CurrentPerson 时(在没有 CollectionView 的清晰绑定之前,它工作正常)此更改不会显示在绑定的 ComboBox 中。
我相信,在那之后为了从 VM 设置 CurrentItem,我们必须以某种方式访问 View(我们不会从 MVVM 中的 ViewModel 访问 View),并调用 MoveCurrentTo 方法来强制 View 显示 currentItem 更改。
因此,通过添加额外的视图功能(排序),我们失去了与现有视图模型的双向绑定,我认为这不是预期的行为。
有没有办法在这里保留双向绑定?或者我做错了什么。
编辑:当我像这样重写 CurrentPerson 设置器时,实际情况可能会更复杂:
set
{
if (m_AvailablePersons.Contains(value)) {
m_Person = m_AvailablePersons.Where(p => p.Equals(value)).First();
}
else throw new ArgumentOutOfRangeException("value");
NotifyPropertyChanged("CurrentPerson");
}
它可以工作
fine!
它的错误行为,或者有解释吗?由于某些原因,即使Equals 被重载,它也需要人对象的引用相等。
我真的不明白为什么它需要引用相等,所以我添加一个 赏金 来解释为什么正常的 setter 不起作用,当 Equal 方法重载时,可以清楚地在使用它的“修复”代码中可以看到
【问题讨论】:
-
+1 很好地发现了与 ComboxBoxes 一起使用的 CollectionViewSources 中的一个真正缺陷!
标签: c# silverlight silverlight-4.0 collectionviewsource