Search code examples
c#wpfxamldatatemplate

How can I Access to template controls in datagrid?


I'm trying to access a control which is inside the control template of a datagrid control in code behind.

myxaml.xaml :

<DataGrid >
.
.
.
<DataGridTemplateColumn x:Name="discountGridTextcolumn" >
    <DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
        <StackPanel Orientation="Horizontal">
            <TextBox Name="discountText"/>
            <ComboBox x:Name="discountType"/>
        </StackPanel>
    </DataTemplate>
</DataGridTemplateColumn.CellTemplate>
.
.
.

mybehind.cs :

var comboBox = GetTemplateChild("discountType");

I get null reference.


Solution

  • If It return null,you must place them in the OnApplyTemplate() method: for example

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
    
       var comboBox = GetTemplateChild("discountType") as ComboBox;
    }
    

    Also try this How to access Control Template parts from Code Behind

    Updated

    From How to: Find DataTemplate-Generated Elements:

    DataGridRow row = (DataGridRow)(yourgrid.ItemContainerGenerator.ContainerFromItem(yourgrid.SelectedItem));
    DataGridDetailsPresenter presenter = FindVisualChild<DataGridDetailsPresenter>(row);
    DataTemplate template = presenter.ContentTemplate;
    ComboBox Com= (ComboBox)template.FindName("discountType", presenter);
    

    FindVisualChild Function:

    private childItem FindVisualChild<childItem>(DependencyObject obj)
        where childItem : DependencyObject
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(obj, i);
            if (child != null && child is childItem)
                return (childItem)child;
            else
            {
                childItem childOfChild = FindVisualChild<childItem>(child);
                if (childOfChild != null)
                    return childOfChild;
            }
        }
        return null;
    }
    

    Another solution How to access objects (comboBox, TextBox...) in DataTemplate