我有一个用 WPF Toolkit 定义的 DataGrid。此 DataGrid 的 CellEditingTemplate 在运行时与构建 FrameworkElementFactory 元素的自定义函数相关联。
现在我必须访问插入到 CellEditingTempleta 的 DataTemplate 中的控件,但我不知道该怎么做。
在网上我发现了一个有用的 ListView Helper...
public static class ListViewHelper
{
public static FrameworkElement GetElementFromCellTemplate(ListView listView, Int32 column, Int32 row, String name)
{
if (row >= listView.Items.Count || row < 0)
{
throw new ArgumentOutOfRangeException("row");
}
GridView gridView = listView.View as GridView;
if (gridView == null)
{
return null;
}
if (column >= gridView.Columns.Count || column < 0)
{
throw new ArgumentOutOfRangeException("column");
}
ListViewItem item = listView.ItemContainerGenerator.ContainerFromItem(listView.Items[row]) as ListViewItem;
if (item != null)
{
GridViewRowPresenter rowPresenter = GetFrameworkElementByName<GridViewRowPresenter>(item);
if (rowPresenter != null)
{
ContentPresenter templatedParent = VisualTreeHelper.GetChild(rowPresenter, column) as ContentPresenter;
DataTemplate dataTemplate = gridView.Columns[column].CellTemplate;
if (dataTemplate != null && templatedParent != null)
{
return dataTemplate.FindName(name, templatedParent) as FrameworkElement;
}
}
}
return null;
}
private static T GetFrameworkElementByName<T>(FrameworkElement referenceElement) where T : FrameworkElement
{
FrameworkElement child = null;
for (Int32 i = 0; i < VisualTreeHelper.GetChildrenCount(referenceElement); i++)
{
child = VisualTreeHelper.GetChild(referenceElement, i) as FrameworkElement;
System.Diagnostics.Debug.WriteLine(child);
if (child != null && child.GetType() == typeof(T))
{
break;
}
else if (child != null)
{
child = GetFrameworkElementByName<T>(child);
if (child != null && child.GetType() == typeof(T))
{
break;
}
}
}
return child as T;
}
}
此代码适用于 ListView 对象,但不适用于 DataGrid 对象。
如何在 DataGrid 中使用这样的东西?