我有一个WPF DataGrid控件,它的SelectionUnit为"FullRow“,SelectionMode为"Extended”,我正在以编程方式选择其中的一项(通常是第一项)。选择是可行的,但出于某种原因,任何形式的程序化选择似乎都会破坏shift-select多选功能。
如果我单击DataGrid中的另一项(所以我刚才单击的项是唯一选中的项),那么shift+select将起作用。只有当我以编程方式选择了该项时,它似乎才会崩溃。此外,在这两种情况下,按住case并单击都可以选择多个项目--似乎只有shift-select被破坏。
我尝试过以编程方式选择单个项目的各种形式,从简单的myGrid.SelectedIndex = 0到使用数据网格的ItemContainerGenerator来获取DataGridRow对象的实例并在其上设置IsSelected = true,但都无济于事。
重复--项目的程序化选择可以工作,但它会破坏shift-click选择。
以前有没有人遇到过这种情况?我尝试在以编程方式选择的DataGridRow实例上设置焦点,但似乎没有帮助?
发布于 2021-01-24 21:47:29
我在这个问题上挣扎了好几天,尝试了很多我在互联网上找到的东西。最后,通过研究DataGrid的源代码,我找到了适合我的解决方案。在DataGrid中,我注意到一个名为_selectionAnchor的成员变量,并猜测这一定是用户在网格中展开选择时的起点。我的解决方案是将此成员设置为所选行的第一个单元格。如果在代码中选择了一行,则此修复将确保在展开选择时从选定行开始。
请注意,我使用了this issue中的代码来启用多选。然后,在文件MainWindow.xaml.cs中,我添加了以下代码:
private void ExampleDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ExampleDataGrid.SelectedItems.Count > 0)
{
ExampleDataGrid.ScrollIntoView(ExampleDataGrid.SelectedItems[0]);
// Make sure that when the user starts to make an extended selection, it starts at this one
foreach (var cellInfo in ExampleDataGrid.SelectedCells)
{
if (cellInfo.Column.DisplayIndex == 0)
{
var cell = GetDataGridCell(cellInfo);
cell?.Focus();
var field = typeof(DataGrid).GetField("_selectionAnchor", BindingFlags.NonPublic | BindingFlags.Instance);
field?.SetValue(ExampleDataGrid, cellInfo);
break;
}
}
}
}
public DataGridCell GetDataGridCell(DataGridCellInfo cellInfo)
{
var cellContent = cellInfo.Column.GetCellContent(cellInfo.Item);
if (cellContent != null)
{
return (DataGridCell)cellContent.Parent;
}
return null;
}在xaml文件中:
<vm:CustomDataGrid x:Name="ExampleDataGrid" ItemsSource="{Binding ImportItems}"
SelectedItemsList="{Binding SelectedImportItems, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
AutoGenerateColumns="False" SelectionMode="Extended" IsReadOnly="True" CanUserAddRows="False"
SelectionChanged="ExampleDataGrid_SelectionChanged">https://stackoverflow.com/questions/7151598
复制相似问题