WPF数据网格单元格,单元格信息和选定单元格+自定义选择
本文关键字:单元格 选择 自定义 信息 数据 数据网 网格 WPF | 更新日期: 2023-09-27 18:17:57
我想在WPF数据网格中操纵选择,但是我在访问实际单元格和设置焦点并将其标记为选中时遇到问题。
-
谁能解释我:为什么没有一些简单的方法来获得**DatagridCell**从**DatagridCellInfo**? - 为什么几乎没有人使用WPF数据网格?
- 有一个简单的方法如何使自己的选择模式为WPF数据网格?
我的问题是什么
我想使自定义选择在WPF Datagrid上选择更多单元格(一个接一个)而不按Ctrl。我做得很好,但我有问题,当我想取消选择一个选定的单元格-只需点击它。把它从列表中删除不成问题。问题是,当它被点击时,它被聚焦并突出显示,而所有其他被选中的都关闭了它们的突出显示。如果我选择另一个没有被选中的单元格所有被选中的单元格都会被正确地突出显示。问题只在取消选择。
我的代码:
XAML:
<Window x:Class="SelectionTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style TargetType="DataGridCell">
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="DataGridCell_PreviewMouseLeftButtonDown"></EventSetter>
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="Pink"></Setter>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<DataGrid
Name="mydatagrid"
Width="Auto" Height="Auto"
HeadersVisibility="All"
AutoGenerateColumns="True" IsReadOnly="True"
SelectionMode="Extended" SelectionUnit="Cell"
CanUserAddRows="False" CanUserDeleteRows="False"
CanUserResizeColumns="False" CanUserResizeRows="False"
CanUserReorderColumns="False" CanUserSortColumns="False"
SelectedCellsChanged="mydatagrid_SelectedCellsChanged"
Padding="10" HorizontalAlignment="Center" VerticalAlignment="Top"
>
</DataGrid>
</Grid>
</Window>
我已经用一些随机的示例类对象列表填充了数据网格。
c#:
private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
DataGridCell cell = sender as DataGridCell;
DataGridCellInfo cellInfo = new DataGridCellInfo(cell);
if ((cell.IsSelected)||(selectedList.Contains(cellInfo))||(selectedCellsList.Contains(cell)))
{
selectedList.Remove(cellInfo);
selectedCellsList.Remove(cell);
cell.IsSelected = false;
mydatagrid.CurrentCell = selectedList[0];
}
else
{
if (selectedList.Count < 7)
{
selectedList.Add(cellInfo);
selectedCellsList.Add(cell);
}
else
{
selectedList.RemoveAt(0);
selectedList.Add(cellInfo);
selectedCellsList.RemoveAt(0);
selectedCellsList.Add(cell);
}
}
mydatagrid.SelectedCells.Clear();
mydatagrid.UnselectAll();
foreach (DataGridCell xcell in selectedCellsList)
{
xcell.IsSelected = true;
xcell.Focus();
}
}
如果这段代码在你看来很难看,那么我很抱歉。但我仍然只是一个小恰帕旺。
什么是我的问题在快捷方式:点击选定的单元格只使它突出显示和聚焦,并突出显示所有其他选定的单元格,这是完全相反的我想要它做的。(如果我点击其他尚未选中的单元格,它会按我想要的方式工作。)
问题1的答案:从DataGridCellInfo获取DataGridCell的快速方法:
public DataGridCell GetDataGridCell(DataGridCellInfo cellInfo)
{
var cellContent = cellInfo.Column.GetCellContent(cellInfo.Item);
if (cellContent != null)
return (DataGridCell) cellContent.Parent;
return null;
}