2010-01-05 86 views
1

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

回答

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)); 

如果你仍然想选择一个单元格,请检查下面的代码会为你工作,它选择与指数2单元格的行索引3

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; 
} 

希望这会有所帮助,至于

+0

谢谢,第一个没有为我工作,即使我有FullRow作为选择模式。第二个将不起作用,因为我的模板是完全自定义的,并且没有CellsPresenter。 – dariusriggins 2010-01-06 15:25:20

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();