C# 按名称查找 WPF 控件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12238599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 22:34:09  来源:igfitidea点击:

Find WPF control by Name

c#wpf

提问by user3357963

I'm after some help finding the best way to refer to controls that have been programmtically built in C#

我正在寻求一些帮助,以找到引用在 C# 中以编程方式构建的控件的最佳方法

If I pre include a label in XAML and name it marketInfothen in code I can set the Tagproperty with something like

如果我在 XAML 中预先包含一个标签并命名它marketInfo然后在代码中我可以Tag用类似的东西设置属性

marketInfo.Tag = timeNow;

However, I'm building controls and assigning each a name using something similar to

但是,我正在构建控件并使用类似于

System.Windows.Controls.Label lbl = new System.Windows.Controls.Label();
lbl.Content = market.name + " - " + DateTime.Now.ToLocalTime().ToLongTimeString();
lbl.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Left;
lbl.Height = 40;
lbl.Name = @"_" + "marketInfo" + countMarket;

How do I refer to these controls from another method? I've read a few posts which suggest using the visualtreehelperbut this appears to require looping controls to find a particular control. Is there a way to access a control by name to avoid looping?

我如何从另一种方法中引用这些控件?我已经阅读了一些建议使用 的帖子,visualtreehelper但这似乎需要循环控件才能找到特定控件。有没有办法按名称访问控件以避免循环?

eg something similar to

例如类似的东西

//pseudo code
SomeControl("_marketInfo5").Tag = timeNow;

Thank you

谢谢

采纳答案by Kevin Gosse

There's at least two ways to do that:

至少有两种方法可以做到这一点:

  • Use the FindNamemethod of the parent container to find the control (but it'll internally involve looping, like the visualtreehelper)

  • Create a dictionary to store a reference for each control you create

    var controls = new Dictionary<string, FrameworkElement>();
    controls.Add("_marketInfo5", lbl);
    

    Then you can do:

    controls["_marketInfo5"].Tag = timeNow;
    
  • 使用FindName父容器的方法来查找控件(但它内部会涉及循环,如visualtreehelper)

  • 创建一个字典来存储您创建的每个控件的引用

    var controls = new Dictionary<string, FrameworkElement>();
    controls.Add("_marketInfo5", lbl);
    

    然后你可以这样做:

    controls["_marketInfo5"].Tag = timeNow;
    

回答by mehdi

You can use XamlQuery for finding your controls at run-time.XamlQuery In CodePlex

您可以使用 XamlQuery 在运行时查找控件。CodePlex 中的 XamlQuery

XamlQuery.Search(RegisterGrid, "Label[Name=_marketInfo5]").SetValue(Control.TagProperty, timeNow);