繁体   English   中英

如何对控件进行类型转换并访问其属性?

[英]How to Typecaste a control and access its properties?

IDE:Visual Studio,C#.net 4.0

我有两个相同的用户控件uc1和uc2,并且都有一个名为txtbox1的文本框
现在看到此代码,并且textbox1在设计器中是公共的,因此可以在form1.cs中进行评估。Form 1是具有uc1和uc2的简单Windows窗体。

在form1中,请参见我在onLoad_form1方法中调用的此函数。

UserControl currentUC; //Global variable;  

public void loadUC(string p1)
{
  //Here I want:
  if(p1 == "UC1)
  {
      currentUC = uc1;
  }
  if(p1 == "UC2)
  {
      currentUC = uc2;
  }
}

比另一个函数调用基于currentUC值更新textbox1

//on load
currentUC.textbox1.text = "UC1 called";

//Here I am getting error "currentUc does not contains definition for textbox1"  

如果我这样做:uc1.textbox1.text =“ UC1文本”; uc2.textbox1.text =“ UC1文本”; //可以,但是基于p1字符串变量,我想将控件设置为uc1或uc2,而不是访问其子控件。 请建议如何执行此操作。

请不要告诉其他问题是否阻止,因为我必须在各种地方使用此功能。

谢谢。

@李答案:-仅适用于文本框,但我有两个用户控件,即两个不同的用户控件而不是它的实例。 UserControlLeft和UserControlRight都具有相同的文本框,列表框等(对设计进行了较小的更改),我想基于一些字符串“ left”和“ right”来访问/加载它。

由于文本框具有相同的名称,因此您可以在“ Controls集合中查找它们:

TextBox tb = (TextBox)currentUC.Controls["textbox1"];
tb.Text = "UC1 called";

更好的解决方案是在您的用户控件类中添加一个属性,以设置内部文本属性,例如

public class MyUserControl : UserControl
{
    public string Caption
    {
        get { return this.textbox1.Text; }
        set { this.textbox1.Text = value; }
    }
}

我认为您在这里混合了几件事。

  1. 首先,您说您有2个完全相同的用户控件,是指ascx文件相同,还是页面上有2个相同用户控件的实例?

让我们使用所有有效的选项:

1.要找到一个控件并将其强制转换:

假设您有以下aspx代码段:

<div>
    <uc1:MyCustomUserControl id="myControl" runat="server" />
    <uc1:MyCustomUserControl id="myControl2" runat="server" />
</div>

如果现在要访问控件,则应执行以下操作:

public void Page_Load()
{
    var myControl ((MyCustomUserControl)FindControl("MyControlName"));

    // On 'myControl' you can now access all the public properties like your textbox.
}

在WPF中,您可以这样操作:

//加载MAINFORM

public void SetText(string text)
{
   CLASSOFYOURCONTROL ctrl = currentUC as CLASSOFYOURCONTROL ;

   ctrl.SetText(text);
}

//在您的控件SUB中

public void SetText(string text)
{
   textbox1.text = "UC1 called"

}

我认为这也应该在winforms中工作。 而且比直接从子控件访问控件更干净

@李的方法很好。 另一种方法是将公共属性与公共设置器一起使用(并且文本框不需要以这种方式公开)。

或接口(通过这种方式,您不必理会给定时刻的班级-如果没有):

public interface IMyInterface
{
  void SetTextBoxText(string text);
}

public partial class UC1: UserControl, IMyInterface
{
   public void SetTextBoxText((string text)
   {
       textBox1.Text=text;
   }

//...
}

public partial class UC2: UserControl, IMyInterface
{
   public void SetTextBoxText((string text)
   {
       textBox1.Text=text;
   }

//...
}

使用代码:

((IMyInterface)instanceOfUC1).SetTextBoxText("My text to set");
((IMyInterface)instanceOfUC2).SetTextBoxText("My text to set");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM