为什么“this.ContentTemplate.FindName"会在它自己的模板上抛出一个 InvalidOperationException? [英] Why would 'this.ContentTemplate.FindName' throw an InvalidOperationException on its own template?

查看:54
本文介绍了为什么“this.ContentTemplate.FindName"会在它自己的模板上抛出一个 InvalidOperationException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧……这让我难住了.我在我的 UserControl 子类中覆盖了 OnContentTemplateChanged.我正在检查为 newContentTemplate 传入的值实际上是否等于 this.ContentTemplate (它确实如此)但是当我调用它时...

Ok... this has me stumped. I've overridden OnContentTemplateChanged in my UserControl subclass. I'm checking that the value passed in for newContentTemplate does in fact equal this.ContentTemplate (it does) yet when I call this...

var textBox = this.ContentTemplate.FindName("EditTextBox", this);

...它抛出以下异常...

...it throws the following exception...

此操作仅对应用了此模板的元素有效."

"This operation is valid only on elements that have this template applied."

根据另一个相关问题中的评论者的说法,他说您应该传入控件的内容展示器,而不是控件本身,所以我然后尝试了这个...

Per a commenter in another related question, he said you're supposed to pass in the content presenter for the control, not the control itself, so I then tried this...

var cp = FindVisualChild<ContentPresenter>(this);

var textBox = this.ContentTemplate.FindName("EditTextBox", cp);

...其中 FindVisualChild 只是 MSDN 示例(见下文)中用于查找相关内容演示者的辅助函数.当 cp 被找到时,它也会抛出同样的错误.我被难住了!!

...where FindVisualChild is just a helper function used in MSDN's example (see below) to find the associated content presenter. While cp is found, it too throws the same error. I'm stumped!!

这里是参考的辅助函数...

Here's the helper function for reference...

private TChildItem FindVisualChild<TChildItem>(DependencyObject obj)
where TChildItem : DependencyObject {

    for(int i = 0 ; i < VisualTreeHelper.GetChildrenCount(obj) ; i++) {

        var child = VisualTreeHelper.GetChild(obj, i);

        if(child is TChildItem typedChild) {
            return typedChild;
        }
        else {
            var childOfChild = FindVisualChild<TChildItem>(child);
            if(childOfChild != null)
                return childOfChild;
        }
    }

    return null;
}

推荐答案

在调用 FindName 方法之前显式应用模板将防止此错误.

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

this.ApplyTemplate(); 

这篇关于为什么“this.ContentTemplate.FindName"会在它自己的模板上抛出一个 InvalidOperationException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆