“FindName” doesn't work if an element added in code

有些话、适合烂在心里 提交于 2019-12-06 07:38:04

问题


In a WPF app, if a ContentControl is declared in XAML,

<Grid Name="MyGrid">
    <ContentControl Name="MyContentControl" />
</Grid>

then I can easily reference it in code using FindName:

ContentControl cc = FindName("MyContentControl") as ContentControl;
cc.Content = ...

But if I add the ContentControl in code instead:

 ContentControl contentcntr = new ContentControl();
 contentcntr.Name = "MyContentControl";
 this.MyGrid.Children.Add(contentcntr);

The FindName doesn't find it.

What's wrong with it in the second case? What's the difference?


回答1:


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.)



来源:https://stackoverflow.com/questions/10260122/findname-doesnt-work-if-an-element-added-in-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!