我有一个数据网格,在最初加载时可以正确排序。但是当我添加一个项目时它不会更新。添加新项目时如何更新和排序网格?
<!-- This works for the initial sort, but when members get added to the collection
the sort doesn't get updated. That's because CollectionViewSource doesn't
implement INotifyPropertyChanged. -->
<UserControl.Resources>
<CollectionViewSource x:Key="SortedApplications" Source="{Binding Applications}">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="Name" Direction="Ascending"/>
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
</UserControl.Resources>
一种选择是在 View 模型中对集合进行排序。但是,如果我在 Foo 中显示所有 Bars,则我必须将 Bars 分解为它自己的属性(在 View 模型中),这样我才能对它们进行排序。
如果可能的话,我想在不使用 View 的代码隐藏的情况下执行此操作,因为我试图不将代码放在那里。
最佳答案
默认情况下,DataGrid 支持排序,而无需指定 SortDescription。事实上,我认为您看到的问题是您的 SortDescription 覆盖了 DataGrid 的排序。我会推荐两件事之一:
如果您计划自己管理 SortDescriptions,请记住在添加新集合之前清除 SortDescriptions 集合,以便排序顺序正确。
更新:
如果在将新项目添加到它绑定(bind)到的集合中时 DataGrid 没有更新,那么您的集合不会引发 CollectionChanged 事件。确保你绑定(bind)到实现 INofityCollectionChanged 的东西——比如 ObservableCollection。
更新:
这是一个按排序顺序插入项目的示例。您的代码有何不同?
XAML:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase" Title="MainWindow">
<Window.Resources>
<CollectionViewSource x:Key="SortedApplications" Source="{Binding Items}">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="Age" Direction="Ascending"/>
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
</Window.Resources>
<StackPanel>
<Button Content="Add Item" Click="AddItem_"/>
<DataGrid ItemsSource="{Binding Source={StaticResource SortedApplications}}"/>
</StackPanel>
</Window>
代码:
public partial class MainWindow : Window
{
public ObservableCollection<Person> Items { get; set; }
public MainWindow()
{
DataContext = this;
Items = new ObservableCollection<Person>();
Items.Add(new Person { Name = "Foo", Age = 1 });
Items.Add(new Person { Name = "Bar", Age = 3 });
Items.Add(new Person { Name = "Foo", Age = 31 });
Items.Add(new Person { Name = "Bar", Age = 42 });
InitializeComponent();
}
private void AddItem_(object sender, RoutedEventArgs e)
{
Items.Add(new Person { Name = "test", Age = DateTime.Now.Second});
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
关于wpf - 添加项目时如何更新数据网格排序(使用 MVVM 且无代码隐藏),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11277910/