FindName returning null

前端 未结 2 371
青春惊慌失措
青春惊慌失措 2020-12-11 06:00

I\'m writing a simple tic tac toe game for school. The assignment is in C++, but the teacher has given me permission to use C# and WPF as a challenge. I\'ve gotten all the g

相关标签:
2条回答
  • 2020-12-11 06:40

    You have to create a new NameScope for your window:

    NameScope.SetNameScope(this, new NameScope());
    

    Then you register name of your label with the window:

    RegisterName(statusDisplay.Name, statusDisplay);
    

    So this seems to be all you need to do to make FindName() work.

    0 讨论(0)
  • 2020-12-11 06:51

    FindName operates on the XAML namescope of the calling control. In your case, since the control is created entirely within code, that XAML namescope is empty -- and that's why FindName fails. See this page:

    Any additions to the element tree after initial loading and processing must call the appropriate implementation of RegisterName for the class that defines the XAML namescope. Otherwise, the added object cannot be referenced by name through methods such as FindName. Merely setting a Name property (or x:Name Attribute) does not register that name into any XAML namescope.

    The easiest way to fix your problem is to store a reference to your StatusDisplay label in the class as a private member. Or, if you want to learn how to use the VisualTreeHelper class, there's a code snippet at the bottom of this page that walks the visual tree to find the matching element.

    (Edited: Of course, it's less work to call RegisterName than to use the VisualTreeHelper, if you don't want to store a reference to the label.)

    I'd recommend reading the first link in its entirety if you plan on using WPF/Silverlight in any depth. Useful information to have.

    0 讨论(0)
提交回复
热议问题