如何通过名称字符串获取WPF XAML中动态生成的元素
解决WPF中通过名称访问代码生成元素的问题
你的问题出在查找名称的范围不对:你调用this.FindName()时,是在当前控件(如窗口、页面)的NameScope中查找,但你生成的元素是注册到_container的NameScope里的,所以直接用this找不到目标元素。
以下是两种可行的解决方法:
方法一:直接调用容器的FindName方法
既然元素注册在_container的NameScope下,直接通过容器对象调用FindName即可:
var _node = _container.FindName("label_" + index.ToString()); if (_node != null && _node is Label) { Label _element = _node as Label; _element.Content = "another value"; // 在这里修改其他需要调整的属性 }
方法二:通过NameScope.GetNameScope获取容器的命名空间再查找
如果_container在当前代码上下文不是直接可访问的,可以先获取它的NameScope实例,再执行查找:
var targetNameScope = NameScope.GetNameScope(_container); var _node = targetNameScope.FindName("label_" + index.ToString()); if (_node != null && _node is Label) { Label _element = _node as Label; // 执行属性修改操作 }
额外注意事项
- 确保元素的注册顺序正确:先将元素添加到
_container.Children,再调用_container.RegisterName(你的示例代码顺序是对的,保持即可)。 - 确认
_container的NameScope已经通过NameScope.SetNameScope正确初始化,这一步你已经完成,无需改动。
内容的提问来源于stack exchange,提问作者Dave
相关产品推荐
相关产品推荐

