'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 1:[1]

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.

Solution 2:[2]

Use RegisterName instead of nextButton.Name = "NextBtn";

var nextButton = new Button();
RegisterName("NextBtn", nextButton); // <-- here
next.Children.Add(nextButton);

You can then find it with:

this.FindName("NextBtn")

Solution 3:[3]

You could find the button manually, for example:

foreach (var child in next.Children)
{
    if (child is Button && (child as Button).Name == "NextBtn")
        ;// do what you want with this child
}

Or:

var btn = next.Children.OfType<Button>().FirstOrDefault(q => q.Name == "NextBtn");
if (btn != null)
    ;// do what you want

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2
Solution 3