WPF DataGrid点击某单元格时多行选择,选择5行(遇到某行含有特殊字符则过滤),右击操作弹出新窗口,并把这五行数据带入显示在新窗口
XMAL代码
<DockPanel>
<StackPanel Orientation ="Horizontal">
<DataGrid x:Name="DataGridLists" DockPanel.Dock="Left" AutoGenerateColumns = "False" FontSize="14" Width="1000" SelectedCellsChanged="DataGridName_SelectedCellsChanged" >
<DataGrid.Columns>
<DataGridTextColumn IsReadOnly="True" Width="200" Header = "ItemOne" Binding = "{Binding ItemOne}" />
<DataGridTextColumn IsReadOnly="True" Width="200" Header = "ItemTwo" Binding = "{Binding ItemTwo}" />
<DataGridTextColumn IsReadOnly="True" Width="200" Header = "ItemThree" Binding = "{Binding ItemThree}" />
<DataGridTextColumn IsReadOnly="True" Width="200" Header = "ItemFour" Binding = "{Binding ItemFour}" />
</DataGrid.Columns>
<DataGrid.CellStyle>
<Style TargetType="{x:Type DataGridCell}">
<EventSetter Event="MouseDoubleClick" Handler="DataGridName_MouseDoubleClick"/>
<Setter Property="HorizontalAlignment" Value="Center" />
</Style>
</DataGrid.CellStyle>
</DataGrid>
</StackPanel>
</DockPanel>
后端代码
private void DataGridName_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
// 获取选中单元格所在的行号
int rowIndex = DataGridLists.Items.IndexOf(DataGridLists.CurrentItem);
DataGridCell cell = sender as DataGridCell;
// 如果行号小于5,则从第一行开始选中5行
if (rowIndex < 5)
{
DataGridLists.SelectedCellsChanged -= DataGridName_SelectedCellsChanged; // 取消事件处理程序
DataGridLists.SelectedItems.Clear();
for (int i = 0; i < 5; i++)
{
DataGridRow selectedRow = (DataGridRow)DataGridLists.ItemContainerGenerator.ContainerFromIndex(i);
if (selectedRow != null)
{
selectedRow.IsSelected = true;
}
DataGridLists.SelectedItems.Add(DataGridLists.Items[i]);
}
// 弹出新窗口
NewWindow obj = new NewWindow();
obj.Show();
DataGridLists.SelectedCellsChanged += DataGridName_SelectedCellsChanged; // 重新启用事件处理程序
}
// 如果行号大于等于5,则选中当前行和前4行
else
{
DataGridLists.SelectedCellsChanged -= DataGridName_SelectedCellsChanged; // 取消事件处理程序
DataGridLists.SelectedItems.Clear();
for (int i = rowIndex - 4; i <= rowIndex; i++)
{
DataGridLists.SelectedItems.Add(DataGridLists.Items[i]);
}
DataGridLists.SelectedCellsChanged += DataGridName_SelectedCellsChanged; // 重新启用事件处理程序
}
// 过滤特殊字符
foreach (var item in DataGridLists.SelectedItems)
{
for (int i = 0; i < DataGridLists.Columns.Count; i++)
{
string value = (DataGridLists.Columns[i].GetCellContent(item) as TextBlock).Text;
if (value.Contains("xxx"))
{
DataGridLists.SelectedItems.Remove(item);
break;
}
}
}
}