0

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.

4

2 回答 2

2

Went through many places and finally made my own solution, it is quite easy:

Let's say we want to get access to a CheckBox named "mycb" in row 0 column 2 of your dataGrid:

ContentPresenter cell = dataGrid.Columns[2].GetCellContent(dataGrid.Items[0]) as ContentPresenter;
CheckBox cb = (CheckBox)cell.ContentTemplate.FindName("mycb", cell);
于 2020-11-12T23:29:47.140 回答
1

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

于 2012-12-30T07:35:33.483 回答