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,745
  • 37
  • 112
  • 180

1 Answers1

10

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.
  • 166,899
  • 29
  • 327
  • 400