引用动态创建的控件? [英] Referencing a dynamically created control?

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

问题描述

我知道如何在c#中创建动态控件:

I know how to create a dynamic control in c#:

TextBlock tb = new TextBlock();
tb.Text = "This is a new textblock";

但是,如何通过代码引用这个新创建的控件?
我浏览了一个解决方案的网络,并发现了这个代码:

But how would I reference this newly created control through code? I browsed the net for a solution, and came across this code:

TextBlock tb = (TextBlock)this.FindName("TB");
tb.Text = "Text property changed"; 

每当我创建一个名称为新的控件时,我会收到一个例外:

Every time I create a new control with a name I get an exception:

TextBlock tb = new TextBlock();
tb.Text = "This is a new textblock";
tb.Name = "TB";




参数不正确。

"The parameter is incorrect."

我做错了什么?任何帮助将不胜感激。

What am I doing wrong? Any help would be greatly appreciated.

提前感谢。

推荐答案

异常参数不正确。可能由于创建的控件的重复名称而发生。

The Exception "The parameter is incorrect." may be occurring because of the duplicate names of the controls created.

对于动态控件部分:您必须将该控件添加到某些Grid或Stackpanel或某些东西。您可以通过获取父控件的内容或子级来引用该动态控件。

For the dynamic control part : you must be adding that control to some Grid or Stackpanel or something. you can reference that dynamic control by getting the content or children of the parent control.

喜欢:

TextBlock Tb= new TextBlock();
tb.Text = "Hello";

ContentPanel.Children.Add(Tb);

//引用:

var content = ContentPanel.Children;
foreach(UIElement uiElem in content)
{
  if(uiElem.GetType() == typeof(TextBlock))
  {
     TextBlock tb = uiElem as TextBlock;
     tb.Text = "Hyee";
  }
}

希望,这可能有帮助。

(注意:我直接在这里写了这段代码,而不是从VS复制,所以请检查语法和拼写。)

(Note: I have written this code directly here and not copied from VS, so please check syntax and spellings.)

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

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