Tag: findname

为什么Window.FindName()没有发现x:子UserCStrol中按钮的名称? AKA NameScopes如何运作?

因此,在下面的示例代码中,我创建了一个UserControl UserControldChild,它是主窗口Window1.xaml的子代。 为什么FindName()方法无法在下面的代码中找到“myButton”? 这必须与WPF XAML NameScopes有关 ,但我还没有找到关于NameScope如何工作的好解释。 有人可以开导我吗? //(xml) Window1.xaml //(c#) Window1.xaml.cs namespace VisualTreeTestApplication { /// /// Interaction logic for Window1.xaml /// public partial class Window1 : Window { public Window1() { InitializeComponent(); Button btnTest = (Button)Application.Current.MainWindow.FindName(“myButton”); // btnTest is null! } } } UserControl如下: //(wpf) UserControlChild.xaml Button //(c#) UserControlChild.xaml.cs (no changes) namespace VisualTreeTestApplication { […]