Search code examples
c#wpfxamlvisual-tree

"FindName" doesn't work if an element added in code


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?


Solution

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