Access to DataTemplate Control of WPF Toolkit DataGridCell at Runtime, How?

Posted by LukePet on Stack Overflow See other posts from Stack Overflow or by LukePet
Published on 2009-11-04T08:38:50Z Indexed on 2010/05/17 2:10 UTC
Read the original article Hit count: 811

I have a DataGrid defined with WPF Toolkit. The CellEditingTemplate of this DataGrid is associated at runtime with a custom function that build a FrameworkElementFactory element.

Now I have to access to control that is inserted inside DataTemplate of CellEditingTempleta, but I do not know how to do.

On web I found a useful 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;
    }
}

this code work with the ListView object but not with the DataGrid object.

How can use something like this in DataGrid?

© Stack Overflow or respective owner

Related posts about wpf

Related posts about wpftoolkit