WPF DataGrid中自定义列DataGridTemplateColumn中的控件获取方法

转帖|其它|编辑:郝浩|2011-03-21 11:50:56.000|阅读 8254 次

概述:WPF DataGrid中自定义列DataGridTemplateColumn非常的方便,但是假如其中有控件,要在后台cs代码中获取嵌入的控件,则非常困难。本来以为非常简单的一个工作,没想到如此复杂,查了好多资料,研究了好长时间才搞出来,可能这个方法太过于复杂,应该还有很简单的获取的方法的,期待更简单的方法吧:

# 界面/图表报表/文档/IDE等千款热门软控件火热销售中 >>

  WPF DataGrid中自定义列DataGridTemplateColumn非常的方便,但是假如其中有控件,要在后台cs代码中获取嵌入的控件,则非常困难。本来以为非常简单的一个工作,没想到如此复杂,查了好多资料,研究了好长时间才搞出来,可能这个方法太过于复杂,应该还有很简单的获取的方法的,期待更简单的方法吧:

  实现思路如下:根据行号和列号,获取DataGridCell 对象,然后根据DataGridCell对象进行查找。

  使用方法:

  假如在DataGridTemplateColumn的<DataTemplate>中第0列有一个Name="txtContent"的TextBlock,在后台cs代码中如此获取。
此控件位于DataGrid选中的这一行的第0列。

  MessageBox.Show(FindCellControl<TextBlock>("txtContent").Text);

   public T FindCellControl<T>(string name) where T : Visual
{
DataRowView selectItem = dataGrid.SelectedItem as DataRowView;
DataGridCell cell = GetCell(dataGrid, dataGrid.SelectedIndex, 0);

   return FindVisualChildByName<T>(cell, name) as T;
}

   public T FindVisualChildByName<T>(Visual parent, string name) where T : Visual
{
if (parent != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i) as Visual;
string controlName = child.GetValue(Control.NameProperty) as string;
if (controlName == name)
{
return child as T;
}
else
{
T result = FindVisualChildByName<T>(child, name);
if (result != null)
return result;
}
}
}
return null;
}

   public static DataGridCell GetCell(DataGrid datagrid, int rowIndex, int columnIndex)
{
DataGridRow rowContainer = GetRow(datagrid, rowIndex);

   if (rowContainer != null)
{
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);

   DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);
if (cell == null)
{
datagrid.ScrollIntoView(rowContainer, datagrid.Columns[columnIndex]);
cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);
}
return cell;
}
return null;
}

   public static DataGridRow GetRow(DataGrid datagrid, int columnIndex)
{
DataGridRow row = (DataGridRow)datagrid.ItemContainerGenerator.ContainerFromIndex(columnIndex);
if (row == null)
{
datagrid.UpdateLayout();
datagrid.ScrollIntoView(datagrid.Items[columnIndex]);
row = (DataGridRow)datagrid.ItemContainerGenerator.ContainerFromIndex(columnIndex);
}
return row;
}

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

  


标签:

本站文章除注明转载外,均为本站原创或翻译。欢迎任何形式的转载,但请务必注明出处、不得修改原文相关链接,如果存在内容上的异议请邮件反馈至chenjj@evget.com

文章转载自:网络转载

为你推荐

  • 推荐视频
  • 推荐活动
  • 推荐产品
  • 推荐文章
  • 慧都慧问
扫码咨询


添加微信 立即咨询

电话咨询

客服热线
023-68661681

TOP