如何等到 ControlTemplate 应用于控件 WPF

how to wait until ControlTemplate applied to the control WPF

我在 CustomControl 中添加了一个名为 AddColumn

的函数
 public void AddColumn(string ColumnHeader)
 {
     Grid MainGrid = this.Template.FindName("MainGrid", this) as Grid;
     Border Header = this.Template.FindName("header", this) as Border;

     if (MainGrid != null)
     {

         MainGrid.Children.Add(HeaderText);
         // ...

         MainGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = 
         MainGrid.Children.Add(...);
         // ...
         GridSplitter Splitter = new GridSplitter() { HorizontalAlignment 
         MainGrid.Children.Add(Splitter);
         // ...
         Grid.SetColumnSpan(Header, ColumnCounter-1);
     }
 }

在该方法中,如您所见,有两次调用ControlTemplate Items。

在完成模板工作之前我无法使用此方法。我的 ControlTemplate 是全局的,我不知道应该在哪里等待它。

我能否以正确的方式等待或应用 ControlTemplate 以便能够在需要时调用此方法?

答案是您的控件应该覆盖 OnApplyTemplate (MSDN)

Derived classes of FrameworkElement can use this method as a notification for a variety of possible scenarios:

  • You can call your own implementation of code that builds the remainder of an element visual tree.

  • You can run code that relies on the visual tree from templates having been applied, such as obtaining references to named elements that came from a template.

  • You can introduce services that only make sense to exist after the visual tree from templates is complete.

  • You can set states and properties of elements within the template that are dependent on other factors. For instance, property values might only be discoverable by knowing the parent element, or when a specific derived class uses a common template.

虽然不知道你的用例;我强烈怀疑这是一个 XY 问题,你真的想要某种绑定 ItemsControl