我有一个视图模型,该模型公开了ListCollectionView和与其绑定的数据网格。出于某些原因,当交换ListCollectionView并从源集合中创建一个新项目时,对于添加到源集合中的新项目的排序会丢失。
源集合是一个ObservableCollection。 对于创建ListCollectionView时源集合中已经存在的项目,排序是正确的。 我不使用GetDefaultView,而是在需要时自己创建ListCollectionView。 将新项目添加到源集合时,不会进行排序,并且项目会显示在列表的末尾。 交换ListCollectionView时会引发INotifyPropertyChanged。
有人知道我为什么会这样吗?
答案 0 :(得分:0)
问题可能出在您创建listcollectionview的过程中。 (您应该已经发布了该代码。)
我将一些实验代码放在一起,可以按预期工作。我只使用一个列表框,但这没什么区别。
<Window.DataContext>
<local:MainWindowViewModel/>
</Window.DataContext>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<Button Command="{Binding AddPersonCommand}" Grid.Column="1"/>
<ListBox ItemsSource="{Binding People}"
>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding LastName}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
Viewmodel
public class MainWindowViewModel : BaseViewModel
{
private RelayCommand addPersonCommand;
public RelayCommand AddPersonCommand
{
get
{
return addPersonCommand
?? (addPersonCommand = new RelayCommand(
() =>
{
People.Add(new Person { FirstName = "Adam", LastName = "Barlow" });
}
));
}
}
private ObservableCollection<Person> people = new ObservableCollection<Person>();
public ObservableCollection<Person> People
{
get { return people; }
set { people = value; }
}
public ListCollectionView LCV { get; set; }
public MainWindowViewModel()
{
LCV = (ListCollectionView)CollectionViewSource.GetDefaultView(People);
LCV.SortDescriptions.Add(
new SortDescription("LastName", ListSortDirection.Ascending));
People.Add(new Person { FirstName = "Chesney", LastName = "Brown" });
People.Add(new Person { FirstName = "Gary", LastName = "Windass" });
People.Add(new Person { FirstName = "Liz", LastName = "McDonald" });
People.Add(new Person { FirstName = "Carla", LastName = "Connor" });
}
}
当我单击按钮时,它将Ken Barlow添加到observablecollection中,并且它出现在列表框的顶部。
我也尝试绑定到LCV:
并实例化通过ctor传入的人。
public class MainWindowViewModel : BaseViewModel
{
private RelayCommand addPersonCommand;
public RelayCommand AddPersonCommand
{
get
{
return addPersonCommand
?? (addPersonCommand = new RelayCommand(
() =>
{
Person person = new Person { FirstName = "Adam", LastName = "Barlow" };
People.Add(person);
}
));
}
}
private ObservableCollection<Person> people = new ObservableCollection<Person>();
public ObservableCollection<Person> People
{
get { return people; }
set { people = value; }
}
public ListCollectionView LCV { get; set; }
public MainWindowViewModel()
{
People.Add(new Person { FirstName = "Chesney", LastName = "Brown" });
People.Add(new Person { FirstName = "Gary", LastName = "Windass" });
People.Add(new Person { FirstName = "Liz", LastName = "McDonald" });
People.Add(new Person { FirstName = "Carla", LastName = "Connor" });
LCV = new ListCollectionView(People);
LCV.SortDescriptions.Add(
new SortDescription("LastName", ListSortDirection.Ascending));
}
}
这也可以。