Why would 'this.ContentTemplate.FindName' throw an InvalidOperationException on its own template?

前端 未结 3 1119
借酒劲吻你
借酒劲吻你 2020-12-09 17:18

Ok... this has me stumped. I\'ve overridden OnContentTemplateChanged in my UserControl. I\'m checking that the value passed in for newContentTemplate does in fact equal th

相关标签:
3条回答
  • 2020-12-09 17:47

    The ContentTemplate isn't applied to the ContentPresenter until after that event. While the ContentTemplate property is set on the control at that point, it hasn't been pushed down to bindings internal to the ControlTemplate, like the ContentPresenter's ContentTemplate.

    What are you ultimately trying to do with the ContentTemplate? There might be a better overall approach to reach your end goal.

    0 讨论(0)
  • 2020-12-09 17:49

    Explicitly applying the template before calling the FindName method will prevent this error.

    this.ApplyTemplate(); 
    
    0 讨论(0)
  • 2020-12-09 17:50

    As John pointed out, the OnContentTemplateChanged is being fired before it is actually applied to the underlying ContentPresenter. So you'd need to delay your call to FindName until it is applied. Something like:

    protected override void OnContentTemplateChanged(DataTemplate oldContentTemplate, DataTemplate newContentTemplate) {
        base.OnContentTemplateChanged(oldContentTemplate, newContentTemplate);
    
        this.Dispatcher.BeginInvoke((Action)(() => {
            var cp = FindVisualChild<ContentPresenter>(this);
            var textBox = this.ContentTemplate.FindName("EditTextBox", cp) as TextBox;
            textBox.Text = "Found in OnContentTemplateChanged";
        }), DispatcherPriority.DataBind);
    }
    

    Alternatively, you may be able to attach a handler to the LayoutUpdated event of the UserControl, but this may fire more often than you want. This would also handle the cases of implicit DataTemplates though.

    Something like this:

    public UserControl1() {
        InitializeComponent();
        this.LayoutUpdated += new EventHandler(UserControl1_LayoutUpdated);
    }
    
    void UserControl1_LayoutUpdated(object sender, EventArgs e) {
        var cp = FindVisualChild<ContentPresenter>(this);
        var textBox = this.ContentTemplate.FindName("EditTextBox", cp) as TextBox;
        textBox.Text = "Found in UserControl1_LayoutUpdated";
    }
    
    0 讨论(0)
提交回复
热议问题