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

别等时光非礼了梦想. 提交于 2020-02-05 08:16:06

问题


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?


回答1:


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

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

You can then find it with:

this.FindName("NextBtn")



回答2:


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.




回答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


来源:https://stackoverflow.com/questions/28393368/how-to-find-dynamically-created-xaml-component-by-name-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!