DataGrid
当我不想让WPF 重新排列我的行时,我遇到了麻烦。
脚步:
- 应用分组
- 按
DataGrid
组内具有重复项的列排序 - 更改不在排序列中的单元格
- 观察行重新排序,将编辑的行移动到在其排序列中具有匹配值的行集的底部
示例(注意按姓氏排序):
FirstName | LastName ^ | Amount
----------+------------+---------
Group:Flinstone
Fred | Flinstone | 42
Wilma | Flinstone | 22
Pebbles | Flinstone | 28
Dino | Flinstone | 64
将 Wilma 的数量从 22 更改为 18 将导致 DataGrid 重新排列如下:
FirstName | LastName ^ | Amount
----------+------------+---------
Group:Flinstone
Fred | Flinstone | 42
Pebbles | Flinstone | 28
Dino | Flinstone | 64
Wilma | Flinstone | 18
如何阻止DataGrid
像这样重新排列行?
DataGrid
注意:如果没有应用任何分组,则不会发生不需要的重新排序。
这是我正在使用的代码:
视图模型:
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"));
}
}
看法:
<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>
模型:
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;
}
}