如何访问datagrid中的模板控件?

时间:2012-12-30 07:23:49

标签: c# wpf xaml datatemplate

我正在尝试访问后面代码中数据网格控件的控件模板内的控件。

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");

我得到空引用。

2 个答案:

答案 0 :(得分:1)

如果返回null,则必须将它们放在OnApplyTemplate()方法中: 例如

public override void OnApplyTemplate()
{
    base.OnApplyTemplate();

   var comboBox = GetTemplateChild("discountType") as ComboBox;
}

另请尝试How to access Control Template parts from Code Behind

<强>更新

来自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功能:

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

另一个解决方案How to access objects (comboBox, TextBox...) in DataTemplate

答案 1 :(得分:0)

走遍了很多地方,终于做出了自己的解决方案,这很容易:

假设我们要访问dataGrid的第0行第2列中名为“ mycb”的CheckBox:

ContentPresenter cell = dataGrid.Columns[2].GetCellContent(dataGrid.Items[0]) as ContentPresenter;
CheckBox cb = (CheckBox)cell.ContentTemplate.FindName("mycb", cell);