在WPF中访问动态创建的控件 [英] Accessing dynamically created controls in wpf

查看:114
本文介绍了在WPF中访问动态创建的控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

我们可以全局访问动态创建的控件吗?
例如:

Hello,

can we access dynamically created controls globally.
for eg:

class Dynamiccontrols
{
  void create()
{
label lbl=new label();
textbox txt=new textbox();
}
void access()
{
// can we access above label and text here.
// or in any other class
lbl.Content="Name"; // like this

}



如果我们在Xaml(designtime)创建控件,则可以在整个类中使用它.



if we create a control at Xaml(designtime) we can use it in through out the class.
How can we do that for controls crested from code.

推荐答案

使用示例,您应该为每个动态创建的控件调用RegisterName:

Using your example, you should call RegisterName for every dynamically created control:

label lbl = new label();
lbl.Name = "ExampleLabel";

RegisterName("ExampleLabel", lbl);



然后,您可以尝试像这样找到控件:



You can then try to locate your control like this:

object j = this.FindName("ExampleLabel");

if (j.GetType() == typeof(Label))
{
   string s = ((Label)j).Name;
}



享受



Enjoy


我找到了VisualTreeHelper [^ ]非常有用,可以将子级放入父控件(动态控件或其他控件)中.
I find the VisualTreeHelper class[^] very useful to get children inside a parent control (dynamic or otherwise).


仅需注意一点:本质上,没有非动态控件之类的东西.所有控件实例总是在运行时创建.在XAML中声明控件的事实不会改变这一点. XAML仅用作设置窗口的数据源.无论如何,所有控件都是在运行时创建和添加的.没什么比这更动态"了.

—SA
Just a note: In essence, there is no such thing as non-dynamic control. All control instances are created during run time, always. The fact that a control is declared in XAML does not change this. XAML is merely used as a data source for setting up a window. All controls are created and added during run time anyway. This is nothing which could be considered as "more dynamic" as that.

—SA


这篇关于在WPF中访问动态创建的控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆