Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

c# - Find WPF control by Name

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

If I pre include a label in XAML and name it marketInfo then in code I can set the Tag property with something like

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 visualtreehelper but this appears to require looping controls to find a particular control. Is there a way to access a control by name to avoid looping?

eg something similar to

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

Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There's at least two ways to do that:

  • Use the FindName method 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;
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...