【问题标题】:access object made by class constructor in c#访问由C#中的类构造函数创建的对象
【发布时间】:2017-04-27 15:08:36
【问题描述】:

我使用 set get 在用户控件类中编写了一个属性,如下所示:

public partial class MyUserControl : UserControl
{   
  public string ServerName { get; set; } 
  public PagingUserControl()
  {
     InitializeComponent();
  }
}

然后通过将此用户控件添加到 Windows 窗体项目,我在属性窗口的“杂项”部分中设置了 ServerName。 现在问题来了,如何从另一个用户控件访问 ServerName ?我想我应该访问由“MyUserControl”的构造函数制作的对象的属性“ServerName”

【问题讨论】:

  • 您可以更改 PageUsingControl() 构造函数以接收字符串 serverName 变量并分配 this.ServerName = serverName public PagingUserControl(string serverName)

标签: c# class constructor user-controls


【解决方案1】:

正确的方法是通过从用户控件中提取作为ServerName 属性值的模型并将两个用户控件绑定到它来反转数据流,有关详细信息,请参阅Windows Forms Data Binding。通过这种方式,您可以节省大量在组件之间进行管道连接和传递数据的时间。


如果您专门寻找如何使用现有代码实现此功能,那么以下步骤也可能对您有所帮助。将用户控件的实例拖放到表单后,设计器将在 Form1.Designer.cs 文件中为其生成一些代码。

// the declaration of your user control
private MyUserControl1 myUserControl11;

private void InitializeComponent()
{
    // the initialization of your user control
    this.myUserControl11 = new WindowsFormsApp3.MyUserControl1();
}

此代码可以从表单访问用户控件的实例。如果您询问如何与另一个控件共享此属性的值,则需要在用户控件中实现 INotifyPropertyChanged

public partial class MyUserControl1 : UserControl, INotifyPropertyChanged

然后将您的父表单订阅到此事件。

private void InitializeComponent()
{
    // subscribe to the user control event
    this.myUserControl11.PropertyChanged += 
        new System.ComponentModel.PropertyChangedEventHandler(
            this.myUserControl11_PropertyChanged);
}

// handle the event by updating the other control
private void myUserControl11_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    textBox1.Text = myUserControl11.ServerName;
}

一旦您实现了通知,您可能会考虑研究如何使用数据绑定以更少的代码实现控件之间的数据传播。希望对您有所帮助!

【讨论】:

    猜你喜欢
    • 2017-03-04
    • 1970-01-01
    • 2016-09-23
    • 1970-01-01
    • 2020-04-02
    • 2012-02-05
    • 1970-01-01
    • 1970-01-01
    • 2017-08-10
    相关资源
    最近更新 更多