Why doesn't Window.FindName () detect x: button name in child UserControl? AKA, how do NameScopes work?

So, in the code example below, I create a UserControl UserControldChild, which is a child of the main Window1.xaml window. Why FindName()could the method not find "myButton" in the code below?

This should be related to the WPF XAML NameScopes , but I have yet to find a good explanation of how NameScope works. Can someone enlighten me?

//(xml) Window1.xaml    
<Window x:Class="VisualTreeTestApplication.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:VisualTreeTestApp="clr-namespace:VisualTreeTestApplication"
    Title="Window1" Height="400" Width="400">
    <Grid>
        <VisualTreeTestApp:UserControlChild/>
    </Grid>
</Window>

//(c#) Window1.xaml.cs
namespace VisualTreeTestApplication
{
  /// <summary>
  /// Interaction logic for Window1.xaml
  /// </summary>
  public partial class Window1 : Window
  {
    public Window1()
    {
      InitializeComponent();
      Button btnTest = (Button)Application.Current.MainWindow.FindName("myButton");
      // btnTest is null!
    }
  }
}

UserControl below:

//(wpf) UserControlChild.xaml
<UserControl x:Class="VisualTreeTestApplication.UserControlChild"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="300" Width="300">
    <Grid x:Name="myGrid">      
        <Button x:Name="myButton" Margin="20" >Button</Button>
    </Grid>
</UserControl>

//(c#) UserControlChild.xaml.cs (no changes)
namespace VisualTreeTestApplication
{
  /// <summary>
  /// Interaction logic for UserControlChild.xaml
  /// </summary>
  public partial class UserControlChild : UserControl
  {
    public UserControlChild()
    {
      InitializeComponent();
    }
  }
}

If you can’t answer this, I found an alternative to using FindName () registered in the message here .

+5
1

- XAML Namescopes.

( ), API- XAML Namescopes.

, FrameworkElement FrameworkContentElement, . FindName() , , WPF thet ree , , , .

Window namescope ( FrameworkContentElement, ). , .

UserControl, Window.FindName() . .

- "" - UserControl. UserControl, UserControl - .

+5

All Articles