15

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

2 Answers2

34

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;
    
Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
Kevin Gosse
  • 38,392
  • 3
  • 78
  • 94
  • The dictionary is a much better method than recursing, especially as the controls I need are all children several layers deep. I should have thought of that one. Thank you. –  Sep 02 '12 at 19:12
  • 3
    This was a great tip, it didn't work for me, but it led me to what did work. I had to use `control.Template.FindName("name")` to get the child I needed. – Fred Jun 18 '14 at 21:23
0

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

XamlQuery.Search(RegisterGrid, "Label[Name=_marketInfo5]").SetValue(Control.TagProperty, timeNow);
mehdi
  • 645
  • 1
  • 9
  • 9