Besuglov Sergey
Besuglov Sergey

Reputation: 506

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?

Upvotes: 2

Views: 2191

Answers (3)

joshuakcockrell
joshuakcockrell

Reputation: 6143

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")

Upvotes: 3

keymusicman
keymusicman

Reputation: 1291

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

Upvotes: 0

Besuglov Sergey
Besuglov Sergey

Reputation: 506

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.

Upvotes: 0

Related Questions