Search code examples
c#wpfxaml

How to find dynamically created XAML component by Name in C#?


How to find dynamically created XAML component by Name in C#?

I created next button and put it into the Stack Panel.

var nextButton = new Button();
nextButton.Name = "NextBtn";
next.Children.Add(nextButton);

then tried to find it with

this.FindName("NextBtn")

and it always comes null.

What am I doing wrong?


Solution

  • As Farhad Jabiyev mentioned I created duplicate.

    As related question (FindName returning null) explaines

    from this page https://msdn.microsoft.com/en-us/library/ms746659.aspx

    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.