" FindName"如果一个元素在代码加入不起作用 [英] "FindName" doesn't work if an element added in code
本文介绍了" FindName"如果一个元素在代码加入不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在一个WPF应用程序,如果ContentControl中在XAML中声明,
In a WPF app, if a ContentControl is declared in XAML,
<Grid Name="MyGrid">
<ContentControl Name="MyContentControl" />
</Grid>
然后我就可以用轻松地引用它在代码 FindName
:
ContentControl cc = FindName("MyContentControl") as ContentControl;
cc.Content = ...
但是,如果我添加ContentControl中的代码,而不是:
But if I add the ContentControl in code instead:
ContentControl contentcntr = new ContentControl();
contentcntr.Name = "MyContentControl";
this.MyGrid.Children.Add(contentcntr);
的
FindName
没有找到它。
什么在第二种情况下是错误的呢?有什么区别?
What's wrong with it in the second case? What's the difference?
推荐答案
在XAML分析器会自动注册该名称在名称范围,如果你创建了这一点,你可能需要的元素做自己使用 RegisterName
。 (有关于 FrameworkElement的$ C $的访问C> 为好。)
The XAML parser automatically registers the names in a namescope, if you create elements like this you may need to do that yourself using RegisterName
. (There is an accessor on FrameworkElement
as well.)
这篇关于" FindName"如果一个元素在代码加入不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文