gpt4 book ai didi

wpf - 为什么 'this.ContentTemplate.FindName' 会在其自己的模板上抛出 InvalidOperationException ?

转载 作者:行者123 更新时间:2023-12-02 02:10:52 24 4
gpt4 key购买 nike

好吧...这让我很困惑。我已经在我的 UserControl 子类中重写了 OnContentTemplateChanged 。我正在检查为 newContentTemplate 传入的值实际上等于 this.ContentTemplate (它确实如此),但当我调用此...

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

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

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

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

var cp = FindVisualChild<ContentPresenter>(this);

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

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

这是供引用的辅助函数...

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 方法之前显式应用模板将防止出现此错误。

this.ApplyTemplate(); 

关于wpf - 为什么 'this.ContentTemplate.FindName' 会在其自己的模板上抛出 InvalidOperationException ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5679648/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com