问题描述
我经过一些帮助寻找指已经programmtically建在C#控制的最好办法
I'm after some help finding the best way to refer to controls that have been programmtically built in C#
如果我预先包括XAML并将其命名标签 marketInfo
然后在代码中,我可以设置标签
属性的东西,如
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;
我如何把这些控件从另一个方法是什么?我阅读过的建议使用 visualtreehelper
但这似乎需要循环控制,以找到一个特定的控制几个职位。类似是否有访问由名称的控制,以避免循环的方法?
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?
如东西
//pseudo code
SomeControl("_marketInfo5").Tag = timeNow;
感谢您
推荐答案
有至少两种方法可以做到这一点:
There's at least two ways to do that:
-
使用
FindName
父容器的方法寻找控制:的(但它会在内部循环涉及,像visualtreehelper)
Use the
FindName
method of the parent container to find the control: http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.findname(v=vs.110).aspx (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;
这篇关于查找名称WPF控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!