Datagrid xaml代码:
<controls:DataGrid Name="dataGrid" AutoGenerateColumns="False" >
<controls:DataGrid.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=Name}" />
</StackPanel>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</controls:DataGrid.GroupStyle>
<controls:DataGrid.Columns>
<controls:DataGridTextColumn Header="Student ID" Width="90*" MinWidth="120" Binding="{Binding StudentId}"/>
<controls:DataGridTextColumn Header="Student Name" Width="90*" MinWidth="120" Binding="{Binding Name}"/>
<controls:DataGridTextColumn Header="Score" Width="100*" MinWidth="150" Binding="{Binding Score}"/>
</controls:DataGrid.Columns>
</controls:DataGrid>
这里有代码:
void LoadDatagrid()
{
List<Student> _studentList = new List<Student>();
_studentList.Add(new Student()
{
StudentId = 1,
Name = "Paul Henriot",
Department = "IT",
Score = 540
});
_studentList.Add(new Student()
{
StudentId = 2,
Name = "John Doe",
Department = "IT",
Score = 620
});
_studentList.Add(new Student()
{
StudentId = 3,
Name = "Aria Cruz",
Department = "ME",
Score = 840
});
_studentList.Add(new Student()
{
StudentId = 4,
Name = "Yoshi Latimer",
Department = "ME",
Score = 450
});
CollectionViewSource viewSource = new CollectionViewSource();
viewSource.GroupDescriptions.Add(new PropertyGroupDescription("Department"));
viewSource.Source = _studentList; ;
dataGrid.ItemsSource = viewSource.View;
}
public class Student
{
public int StudentId{ get; set; }
public string Name { get; set; }
public string Department { get; set; }
public int Score { get; set; }
}
当我尝试在任何一个部门中编辑得分或名称时,在编辑该行后跳转到下来。
需要帮助。
答案 0 :(得分:2)
我认为你的代码错了,GroupStyle的绑定路径应该是“Department”,而不是“Name”。
更改您的代码:
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=Name}" />
</StackPanel>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
到此:
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=Department}" />
</StackPanel>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
它应该可以正常工作。
答案 1 :(得分:0)
这解决了我的问题,我已将SortDescription添加到CollectionViewSource。
CollectionViewSource viewSource = new CollectionViewSource();
viewSource.GroupDescriptions.Add(new PropertyGroupDescription("Department"));
viewSource.SortDescriptions.Add(new System.ComponentModel.SortDescription("Department", System.ComponentModel.ListSortDirection.Ascending));
viewSource.SortDescriptions.Add(new System.ComponentModel.SortDescription("StudentId", System.ComponentModel.ListSortDirection.Ascending));
viewSource.Source = _studentList; ;
dataGrid.ItemsSource = viewSource.View;