即使我设置了SelectionMode="Extended"
和SelectionUnit="FullRow"
,当我调试SelectionChanged
事件时,SelectedItems
中始终只有一个选定的项目}。
这是我的DataGrid
:
<DataGrid Grid.Row="0" AutoGenerateColumns="False" Margin="5,5,5,0"
Name="dgrMembersClub1" ItemsSource="{Binding .}" CanUserAddRows="False"
SelectionMode="Extended" SelectionUnit="FullRow" SelectionChanged="Grid_SelectionChanged">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Joining" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsSelected}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn IsReadOnly="True" Header="Surname" Binding="{Binding Surname}" />
<DataGridTextColumn IsReadOnly="True" Header="Name" Binding="{Binding Name}" />
<DataGridTextColumn IsReadOnly="True" Header="Club" Binding="{Binding Club_Id, Converter={StaticResource ClubName}}" />
<DataGridTextColumn IsReadOnly="True" Header="City" Binding="{Binding City}" />
</DataGrid.Columns>
</DataGrid>
我的Grid_SelectionChanged
事件:
private void Grid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DataGrid grid = (DataGrid)sender;
var test = grid.SelectedItems; //Count == 1 (always)
}
我确实设置了触发器(在App.xaml中),用于更改选定行和交替行的背景和前景画笔。如果相关,请告诉我,我会添加代码。
*编辑*
虽然您正在使用它,但我可以使用一些帮助来获取单元格模板中的复选框。非常好请:))
答案 0 :(得分:0)
DataGrid的SelectedItems属性包含一系列精选的项目......
private void DataGrid_SelectionChanged(object sender,
SelectionChangedEventArgs e)
{
// ... Get SelectedItems from DataGrid.
var grid = sender as DataGrid;
var selected = grid.SelectedItems;
foreach (var item in selected)
{
var dog = item as Dog;
}
}
这个指示性事件处理程序获取SelectedItems并循环遍历它。
然而,有一点需要注意:
“如果SelectionMode属性设置为Single,则为SelectedItems list将只包含SelectedItem属性值。“
来源:http://msdn.microsoft.com/en-us/library/system.windows.controls.datagrid.selecteditems(v=vs.95).aspx
SelectedItems属性继承自IList,因此可以对其进行强制转换并对其执行LINQ操作。它也适用于非连续选择。
的更多提示答案 1 :(得分:0)
private IEnumerable<DataGridRow> GetDataGridRows(DataGrid grid)
{
var itemsSource = grid.ItemsSource as IEnumerable;
if (null == itemsSource) yield return null;
foreach (var item in itemsSource)
{
var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
if (null != row & row.IsSelected) yield return row;
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var rows = GetDataGridRows(dgv_Students);
string id; //Sample =>"85-999888-2"
foreach (DataGridRow dr in rows)
{
id = (dr.Item as tbl_student).code_meli;
MessageBox.Show(id);
}
}