1

我有一个自定义行模板来显示一些数据,它没有在其模板中使用 SelectiveScrollingGrid。我不介意处理我的外部元素上的事件,但我似乎无法弄清楚如何导致“选择”行为。通常,我是通过在活动 DataGridCell 上引发 MouseLeftButtonDownEvent 来引起它的,但是现在我实际上没有任何 DataGridCell,我对如何仅访问 DataGridRow 来复制该行为感到有些困惑。

4

2 回答 2

2

不确定您的模板是什么样子,但我想您可以考虑通过设置它的属性 SelectionUnit="FullRow" 并执行下面的代码来选择网格的整行;它选择索引为 3 的整行

int index = 3;
dataGrid.SelectedItem = dataGrid.Items[index];
dataGrid.ScrollIntoView(dataGrid.Items[index]);
DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromItem(dataGrid.Items[index]);
row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));

如果您仍想选择一个单元格,请检查下面的代码是否适合您,它会为索引为 3 的行选择一个索引为 2 的单元格

int index = 3;
dataGrid.ScrollIntoView(dataGrid.Items[index]);
DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromItem(dataGrid.Items[index]);
if (row != null)
{
    DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);
    DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(2);
    if (cell != null)
    {
        cell.IsSelected = true;
        cell.Focus();
    }
}

GetVisualChild 程序实现:

static T GetVisualChild<T>(Visual parent) where T : Visual
{
    T child = default(T);
    int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
    for (int i = 0; i < numVisuals; i++)
    {
        Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
        child = v as T;
        if (child == null)
        {
            child = GetVisualChild<T>(v);
        }
        if (child != null)
        {
            break;
        }
    }
    return child;
}

希望这会有所帮助,问候

于 2010-01-06T04:54:14.640 回答
0

这就是我最终开始工作的地方,这很丑陋,但可以完成工作。这些元素仅在左键或右键单击时突出显示,因此我也不得不强制重绘,对我来说似乎很难看,但它确实有效。

var row = (DataGridRow)((FrameworkElement)sender).TemplatedParent;
var element = (FrameworkElement)sender;
var parentGrid = this.GetGridFromRow((DataGridRow)element.TemplatedParent);
parentGrid.SelectedItems.Clear();
row.IsSelected = true;
element.InvalidateVisual();
parentGrid.UpdateLayout();
于 2010-01-06T15:28:58.233 回答