如何在 C# 中按名称查找动态创建的 XAML 组件?

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

如何在 C# 中通过名称查找动态创建的 XAML 组件?

我创建了下一个按钮并将其放入堆栈面板。

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

然后尝试用

找到它
this.FindName("NextBtn")

它总是为空。

我做错了什么?

您可以手动找到按钮,例如:

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

或者:

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

正如 Farhad Jabiyev 提到的,我创建了副本。

如相关问题 (FindName returning null) 所述

来自此页面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.

使用RegisterName代替nextButton.Name = "NextBtn";

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

然后您可以通过以下方式找到它:

this.FindName("NextBtn")