如果在代码中添加了元素,则"FindName"不起作用

rem*_*rem 3 c# wpf xaml visual-tree

在WPF应用程序中,如果在XAML中声明了ContentControl,

<Grid Name="MyGrid">
    <ContentControl Name="MyContentControl" />
</Grid>
Run Code Online (Sandbox Code Playgroud)

然后我可以使用FindName以下代码在代码中轻松引用它

ContentControl cc = FindName("MyContentControl") as ContentControl;
cc.Content = ...
Run Code Online (Sandbox Code Playgroud)

但是,如果我在代码中添加ContentControl:

 ContentControl contentcntr = new ContentControl();
 contentcntr.Name = "MyContentControl";
 this.MyGrid.Children.Add(contentcntr);
Run Code Online (Sandbox Code Playgroud)

FindName没有找到它.

在第二种情况下它有什么问题?有什么不同?

H.B*_*.B. 8

XAML解析器会自动在名称范围中注册名称,如果您创建这样的元素,您可能需要自己使用RegisterName.(也有一个存取器FrameworkElement.)