UserControl 子控件和 FindName

发布于 2024-10-10 01:31:04 字数 567 浏览 5 评论 0原文

我有一个 Silverlight UserControl,它使用 ContentPropertyAttribute 公开其子面板之一的 Children 属性。这允许我将子控件添加到页面上的面板:

<local:MyUserControl>
    <TextBox Name="tbTest" />
</local:MyUserControl>

除了页面的“tbTest”字段存在但未初始化之外,这是有效的。仔细检查后发现,InitializeComponent 方法确实尝试定位 TextBox(使用 FindName),但未能成功(返回 null)。

经过一番调查,我发现名称范围是问题所在 - UserControl 有自己的名称范围,因此无法使用页面的 FindName 找到它的子级,但可以使用 UserControl 的 FindName 方法找到。

如何更改 UserControl 以便可以通过 InitializeComponent 方法找到子控件?标准面板(StackPanel、Grid 等)这样做似乎没有任何问题,那么一定有解决方案吗?

谢谢

I have a Silverlight UserControl which uses the ContentPropertyAttribute to exposes the Children property of one of it's child panels. This allows me to add child controls to the panel on my page:

<local:MyUserControl>
    <TextBox Name="tbTest" />
</local:MyUserControl>

This works, apart from the 'tbTest' field of the page being present, but not initialised. On closer inspection, the InitializeComponent method does try to locate the TextBox (with FindName), but fails to do so (returning null).

After some investigation, I've found that namescopes are the problem - the UserControl has it's own namescope, thus it's children can't be located with the page's FindName but can with the UserControl's FindName method.

How can I alter my UserControl so that the child controls are locatable by the InitializeComponent method? The standard Panels (StackPanel, Grid, etc.) don't seem to have any problem doing so, so there must be a solution?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

Bonjour°[大白 2024-10-17 01:31:04

此时可能很难做到,但最好的做法可能是从 ItemsControl 而不是 UserControl 派生控件。那么你就不会遇到名称范围的问题了。

我想作为一种解决方法,您可以使用 VisualTreeHelper 深入了解控件以手动设置 tbTest 字段。

It may be difficult to do at this point but the best course of action would probably be to derive your control from ItemsControl instead of UserControl. Then you wouldn't have the problem with name scopes.

I suppose as a workaround you could do a dive into the control with VisualTreeHelper to manually set the tbTest field.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文