Access WPF template for user control from code

I am trying to access a named grid inside the default template for a custom control from code. But it seems that the template for the control is zero, even after calling ApplyTemplate ().
Is this not possible in control? Here is the code:

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 ... } 
+4
source share
1 answer

You must move your code to the overridden OnApplyTemplate and use the GetTemplateChild method as follows:

 public class TimeTableControl { private Grid contentGrid; protected override void OnApplyTemplate() { base.OnApplyTemplate(); contentGrid = GetTemplateChild("ContentGrid") as Grid; } } 
+10
source

Source: https://habr.com/ru/post/1308123/


All Articles