如何在用户控件 WinForm 中访问托管表单上的控件 [英] How to access controls on hosted form in a user control WinForm

查看:31
本文介绍了如何在用户控件 WinForm 中访问托管表单上的控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Visual Studio 中,如何访问托管用户控件的表单上的控件?例如,当用户控件中的文本框中的文本发生更改时,我希望另一个用户控件中的另一个文本框中的文本发生更改.这两个用户控件都托管在同一个表单上.提前致谢!

In visual studio how do you access a control on a form hosting a user control? For example, when text changes in a text-box in a user control, I want text in another text-box in another user control to change. Both these user controls are hosted on the same form. Thanks in advance!

推荐答案

如果您需要不同的 UI 进行数据输入,我更喜欢有 2 个具有不同 UI 的控件,但我会为它们使用单​​个数据源并处理场景使用数据绑定.

If you need different UI for data entry, I prefer to have 2 controls with different UI, but I will use a single data source for them and handle the scenario using data-binding.

如果您将两个控件绑定到一个数据源,虽然您可以有不同的 UI,但您有一个数据并且两个控件数据是同步的.

If you bind both controls to a single data source, while you can have different UI, you have a single data and both controls data are sync.

你的问题的答案:

你可以在每个控件中定义一个属性来设置TextBoxText.然后你可以处理TextBoxTextChanged事件,然后找到另一个控件并设置text属性:

You can define a property in each control which set Text of TextBox. Then you can handle TextChanged event of the TextBox and then find the other control and set the text property:

控制1

public partial class MyControl1 : UserControl
{
    public MyControl1() { InitializeComponent(); }

    public string TextBox1Text
    {
        get { return this.textBox1.Text; }
        set { this.textBox1.Text = value; }
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        if (Parent != null)
        {
            var control1 = Parent.Controls.OfType<MyControl2>().FirstOrDefault();
            if (control1 != null && control1.TextBox1Text != this.textBox1.Text)
                control1.TextBox1Text = this.textBox1.Text;
        }
    }
}

控制2

public partial class MyControl2 : UserControl
{
    public MyControl2() { InitializeComponent(); }

    public string TextBox1Text
    {
        get { return this.textBox1.Text; }
        set { this.textBox1.Text = value; }
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        if (Parent != null)
        {
            var control1 = Parent.Controls.OfType<MyControl1>().FirstOrDefault();
            if (control1 != null)
                control1.TextBox1Text = this.textBox1.Text;
        }
    }
}

这篇关于如何在用户控件 WinForm 中访问托管表单上的控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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