Referencing a dynamically created control?

守給你的承諾、 提交于 2019-12-14 02:33:47

问题


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.

Thanks in advance.


回答1:


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

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.

Like :

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

ContentPanel.Children.Add(Tb);

//to reference :

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

Hope, it might help.

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




回答2:


Yes you can use reference dynamic controls this way. But another way is that you can also keep a list of the references when you create the controls.



来源:https://stackoverflow.com/questions/11460533/referencing-a-dynamically-created-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!