您可以像这样从网格中获取选定的项目:
<DataGrid Name="dgStudents"
AutoGenerateColumns="False"
SelectionChanged="dgStudents_SelectionChanged">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding ID}" />
<DataGridTextColumn Header="Name" Binding="{Binding Name}" />
<DataGridTextColumn Header="Surname" Binding="{Binding Surname}" />
</DataGrid.Columns>
</DataGrid>
事件处理程序:
private void dgStudents_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems != null && e.AddedItems.Count != 0)
{
foreach (Student item in e.AddedItems)
{
Console.WriteLine(item.ID);
}
}
}
简单的学生班:
class Student
{
public int ID { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
}
如果你想使用上下文菜单试试这个:
<DataGrid Name="dgStudents"
AutoGenerateColumns="False">
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Header="ClassA" Click="ClassA_Click" />
<MenuItem Header="ClassB" Click="ClassB_Click" />
</ContextMenu>
</DataGrid.ContextMenu>
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding ID}" />
<DataGridTextColumn Header="Name" Binding="{Binding Name}" />
<DataGridTextColumn Header="Surname" Binding="{Binding Surname}" />
<DataGridTextColumn Header="Class" Binding="{Binding ClassName}" />
</DataGrid.Columns>
</DataGrid>
MenuItem
在代码隐藏中添加两个事件处理程序:
private void ClassA_Click(object sender, RoutedEventArgs e)
{
if (dgStudents.SelectedItems != null && dgStudents.SelectedItems.Count != 0)
{
foreach (Student item in dgStudents.SelectedItems)
{
item.ClassName = "ClassA";
}
dgStudents.Items.Refresh();
}
}
private void ClassB_Click(object sender, RoutedEventArgs e)
{
if (dgStudents.SelectedItems != null && dgStudents.SelectedItems.Count != 0)
{
foreach (Student item in dgStudents.SelectedItems)
{
item.ClassName = "ClassB";
}
dgStudents.Items.Refresh();
}
}
将学生班级更改为:
class Student
{
public int ID { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string ClassName { get; set; }
}