从代码隐藏访问自定义控件的WPF模板

时间:2023-01-24 22:15:28

i am trying to access a named grid inside a default template for a custom control from code behind.
But it seems that the template for the control is null, even after calling ApplyTemplate().
Is that impossible inside the controls constuctor?
Here's the code:

我试图从代码隐藏的默认模板中访问自定义控件的命名网格。但是,即使在调用ApplyTemplate()之后,控件的模板似乎也为null。控件构造器内部是不可能的?这是代码:

Generic.xaml:
...
<ControlTemplate TargetType="{x:Type local:TimeTableControl}">
    <Grid Name="ContentGrid">
    </Grid>
</ControlTemplate>
...

TimeTableControl.cs:

public TimeTableControl()
{
    ApplyTemplate();
    contentGrid = (Grid)(Template.FindName("ContentGrid", this));  
     //Line above causes null-pointer-exception
     ...
}

1 个解决方案

#1


10  

You should move your code into an overridden OnApplyTemplate and use the GetTemplateChild method like so:

您应该将代码移动到重写的OnApplyTemplate并使用GetTemplateChild方法,如下所示:

public class TimeTableControl {

    private Grid contentGrid;

    protected override void OnApplyTemplate() {

        base.OnApplyTemplate();

        contentGrid = GetTemplateChild("ContentGrid") as Grid;

    }

}

#1


10  

You should move your code into an overridden OnApplyTemplate and use the GetTemplateChild method like so:

您应该将代码移动到重写的OnApplyTemplate并使用GetTemplateChild方法,如下所示:

public class TimeTableControl {

    private Grid contentGrid;

    protected override void OnApplyTemplate() {

        base.OnApplyTemplate();

        contentGrid = GetTemplateChild("ContentGrid") as Grid;

    }

}