デフォルトでは、DataGrid は SortDescription を指定しなくてもソートをサポートします。実際、あなたが見ている問題は、SortDescription が DataGrid の並べ替えをオーバーライドしていることだと思います。次の 2 つのいずれかをお勧めします。
- SortDescription を削除し、DataGrid に並べ替えを処理させる
- CollectionViewSource を ViewModel に移動し、ViewModel を呼び出して SortDescriptions を管理する DataGrid に並べ替えハンドラーを追加します。
SortDescriptions を自分で管理する予定がある場合は、並べ替え順序が正しくなるように、新しいコレクションを追加する前に SortDescriptions コレクションをクリアすることを忘れないでください。
アップデート:
新しいアイテムがバインド先のコレクションに追加されたときに DataGrid が更新されない場合、コレクションは CollectionChanged イベントを発生させていません。ObservableCollectionのように、INofityCollectionChangedを実装するものにバインドしていることを確認してください。
更新:
アイテムを並べ替えた順序で挿入する例を次に示します。あなたのコードはどのように違いますか?
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; }
}