Why can't I access a TextBox by Name with FindName()?

前端 未结 1 773
孤独总比滥情好
孤独总比滥情好 2020-12-10 07:21

Why does FindName() return null in the following example?

XAML:



        
相关标签:
1条回答
  • 2020-12-10 08:27

    This is related to WPF XAML Namescopes.

    Because you add elements to parsed element trees, you need to call RegisterName.

            ...
            TextBox textBox = new TextBox();
            textBox.Name = "FirstName";
            textBox.Text = "test";
    
            this.RegisterName("FirstName", textBox);
            ...
    

    Adding Elements to Parsed Element Trees

    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. Adding a named element to an element tree that has a XAML namescope also does not register the name to the XAML namescope. Although XAML namescopes can be nested, you generally register names to the XAML namescope that exists on the root element, so that your XAML namescope location parallels the XAML namescope that would have been created in an equivalent loaded XAML page. The most common scenario for application developers is that you will use RegisterName to register names into the XAML namescope on the current root of the page. RegisterName is part of one important scenario for finding storyboards that will run as animations. For more information, see Storyboards Overview. If you call RegisterName on an element other than the root element in the same object tree, the name is still registered to the element nearest the root, as if you had called RegisterName on the root element.

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