I am having problems with WPF DataGrid when I don't want to change it.
Steps:
- Apply Grouping
- Sort a
DataGrid by a column with duplicates within a group - Change cell not in sorted column
- Note that rows reorder the movement of the edited row to the bottom of the set of rows that have the corresponding values ββin the sorted column
Example (note sorting by LastName):
FirstName | LastName ^ | Amount ----------+------------+--------- Group:Flinstone Fred | Flinstone | 42 Wilma | Flinstone | 22 Pebbles | Flinstone | 28 Dino | Flinstone | 64
Changing Wilma from 22 to 18 will rearrange the DataGrid as follows:
FirstName | LastName ^ | Amount ----------+------------+--------- Group:Flinstone Fred | Flinstone | 42 Pebbles | Flinstone | 28 Dino | Flinstone | 64 Wilma | Flinstone | 18
How to stop a DataGrid from reordering rows as follows?
Note. Unwanted reordering does not occur if the DataGrid does not have any grouping applied to it.
Here is the code I'm using:
ViewModel:
public class MainViewModel { public ObservableCollection<Item> Items { get; set; } public ListCollectionView ItemsView { get; set; } public MainViewModel() { Items = new ObservableCollection<Item>(); Items.Add(new Item("Fred", "Flinstone", 42)); Items.Add(new Item("Wilma", "Flinstone", 22)); Items.Add(new Item("Pebbles", "Flinstone", 52)); Items.Add(new Item("Dino", "Flinstone", 52)); Items.Add(new Item("Barney", "Rubble", 32)); Items.Add(new Item("Betty", "Rubble", 62)); Items.Add(new Item("BamBam", "Rubble", 42)); Items.Add(new Item("George", "Jetson", 22)); Items.Add(new Item("Jane", "Jetson", 52)); Items.Add(new Item("Judy", "Jetson", 32)); Items.Add(new Item("Elroy", "Jetson", 62)); Items.Add(new Item("Astro", "Jetson", 42)); ItemsView = new ListCollectionView(Items); ItemsView.GroupDescriptions.Add(new PropertyGroupDescription("LastName")); } }
View:
<DataGrid ItemsSource="{Binding ItemsView}"> <DataGrid.GroupStyle> <GroupStyle> <GroupStyle.ContainerStyle> <Style TargetType="{x:Type GroupItem}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type GroupItem}"> <StackPanel> <TextBlock Text="{Binding Path=Name}" /> <ItemsPresenter /> </StackPanel> </ControlTemplate> </Setter.Value> </Setter> </Style> </GroupStyle.ContainerStyle> </GroupStyle> </DataGrid.GroupStyle> </DataGrid>
Model:
public class Item { public string FirstName { get; set; } public string LastName { get; set; } public decimal Amount { get; set; } public Item(string firstName, string lastName, decimal amount) { FirstName = firstName; LastName = lastName; Amount = amount; } }