3

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?

rem
  • 16,105
  • 37
  • 108
  • 179

1 Answers1

9

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

H.B.
  • 142,212
  • 27
  • 297
  • 366