How to access controls on hosted form in a user control WinForm(如何在用户控件 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.
你的问题的答案:
你可以在每个控件中定义一个属性来设置TextBox
的Text
.然后你可以处理TextBox
的TextChanged
事件,然后找到另一个控件并设置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 中访问托管表单上的控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在用户控件 WinForm 中访问托管表单上的控件


- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 输入按键事件处理程序 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04