我在运行时programmaticaly添加了一个元素:
private void AddModule(string modulename, string ip, string description)
{
ModuleInfobox infobox = new ModuleInfobox();
infobox.Modulename = modulename;
infobox.IpAddress = ip;
infobox.Description = description;
infobox.Modulenamecolor = "Lime";
infobox.Name = modulename;
ModulePanel.RegisterName(infobox.Name, infobox);
ModulePanel.Children.Add(infobox);
}
ModuleInfoBox是我的UserControl
。现在我需要对这个对象的引用。我试试这个:
private FindLogicalNodeDelegate delFindLogicalNode;
private FindNameDelegate delFindName;
delegate object FindLogicalNodeDelegate(DependencyObject wantedObject, string name);
delegate object FindNameDelegate(string name);
delFindLogicalNode = new FindLogicalNodeDelegate(LogicalTreeHelper.FindLogicalNode);
delFindName = new FindNameDelegate(ModulePanel.FindName);
在一个帖子中:
object wantedObject = ModulePanel.Dispatcher.BeginInvoke(delFindLogicalNode, DispatcherPriority.Normal, ModulePanel, "modulename").Result;
object wantedObject2 = this.Dispatcher.BeginInvoke(delFindName, DispatcherPriority.Normal, "moduleName").Result;
当我使用调试器时,FindLogicalNode有时会找到引用,但通常不会。 我阅读了以下主题:WPF - FindName Returns null when it should not和"FindName" doesn't work if an element added in code 但我的代码中仍然存在错误