Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 编辑用户控件的多个实例_C#_Wpf_User Controls_Instance_Multiple Instances - Fatal编程技术网

C# 编辑用户控件的多个实例

C# 编辑用户控件的多个实例,c#,wpf,user-controls,instance,multiple-instances,C#,Wpf,User Controls,Instance,Multiple Instances,我对C#还不太熟悉,并且已经创建了多个这样的用户控件实例 StackPanel StkPnl = new StackPanel(); StkPnl = SP; //SP being the static objRef of the StackPanel in the MainWindow for (int i = 0; i < 5; i++) { UserControl UsrCtrl = new UserControl(); UsrCtrl = new UserCont

我对C#还不太熟悉,并且已经创建了多个这样的用户控件实例

StackPanel StkPnl = new StackPanel();
StkPnl = SP; //SP being the static objRef of the StackPanel in the MainWindow 
for (int i = 0; i < 5; i++)
{
    UserControl UsrCtrl = new UserControl();
    UsrCtrl = new UserControl1();
    UserControl1.TB.Text = "Text:"+i;   //TB being the static objRef of the textblock that is in the user control
    UsrCtrl.Name = "UsrCtrl" + i; 
    StkPnl.Children.Add(UsrCtrl);
}
StackPanel StkPnl=new StackPanel();
StkPnl=SP//SP是主窗口中StackPanel的静态对象
对于(int i=0;i<5;i++)
{
UserControl UsrCtrl=新的UserControl();
UsrCtrl=newusercontrol1();
UserControl1.TB.Text=“Text:+i;//TB是用户控件中textblock的静态objRef
UsrCtrl.Name=“UsrCtrl”+i;
StkPnl.Children.Add(UsrCtrl);
}
我想做的是能够调用我独立创建的每个用户控件并编辑特定的textblock.text。例如:编辑UsrCtrl3的文本块,而不更改创建的其他4个用户控件


我发现自己有点难以解释。如果您需要任何澄清,请告诉我,我会尽力解释。

您可以使用以下索引访问集合中的特定元素:

StkPnl.Children[3].TB.Text = "Some Text";  // edit fourth user control (UsrCtrl3)
或者可以使用LINQ搜索名称

方法
SingleOrDefault()
最多需要一个匹配项。如果未找到匹配项,则返回
null

var thirdUserControl = StkPnl.Children.SingleOrDefault(x => x.Name == "UsrCtrl3");

if (thirdUserControl != null)
    thirdUserControl.TB.Text = "Some Text";

您的意思是说,随后将集合中的某个特定用户控件作为目标来更改其文本,而不仅仅是更改它们的创建位置吗?在FOR循环中创建每个用户控件后,我希望调用已创建的特定用户控件(例如,在循环中创建的第三个用户控件),并在该第三个用户控件中编辑textblock。是的,我自己也说得再好不过了。谢谢你的快速回复,这听起来可能是一个愚蠢的问题,但当尝试合并您所说的内容时,我得到一个错误:“System.Windows.UIElement”不包含“TB”的定义,并且找不到接受“System.Windows.UIElement”类型的第一个参数的扩展方法“TB”(您是否缺少using指令或程序集引用?)