开发者

Accessing WPF Template for Custom Control from Code behind

开发者 https://www.devze.com 2022-12-28 12:56 出处:网络
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().

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:

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

TimeTableControl.cs:

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


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

public class TimeTableControl {

    private Grid contentGrid;

    protected override void OnApplyTemplate() {

        base.OnApplyTemplate();

        contentGrid = GetTemplateChild("ContentGrid") as Grid;

    }

}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号