c# - 添加时在窗体中查找UserControl

标签 c# wpf winforms

我编写代码在 Form 中添加 UserControl:

        UserControl edt = new UserControl();
        edt.Name = "ItemEdit";
        frm_Editor frm = new frm_Editor();
        frm.Controls.Add(edt);
        frm.Show();

然后,我在 Form 中找到了 UserControl:

Control[] tbxs = this.Controls.Find("ItemEdit", true);
if (tbxs != null && tbxs.Length > 0)
{
    MessageBox.Show("Found");
}

但是结果为null && tbxs.Length = 0 请指导我解决流程问题。非常感谢!

最佳答案

它适用于这个小程序,它可能会为您指明使用您自己的代码的解决方案。

using System;
using System.Windows.Forms;

namespace FormTest
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Form1 frm = new Form1();
            UserControl edt = new UserControl();
            edt.Name = "ItemEdit";
            frm.Controls.Add(edt);

            Application.Run(frm);
        }
    }
}

using System.Windows.Forms;

namespace FormTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, System.EventArgs e)
        {
            Control[] tbxs = this.Controls.Find("ItemEdit", true);
            if (tbxs != null && tbxs.Length > 0)
            {
                MessageBox.Show("Found");
            }
        }
    }
}

关于c# - 添加时在窗体中查找UserControl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37776720/

相关文章:

c# - 为什么我不能在 xaml 中定义网格模板?

c# - 具有绑定(bind)数据源的空 Datagridview 单元格

c# - 带有子窗体的 Windows 窗体中的 Unity DI

c# - 如何在 .NET 中检测通过串行端口或以太网连接的设备状态的变化

c# - 基于 DependencyProperty 控制样式

c# - 在 DataTable 已经有数据后为 DataTable 设置自动编号

c# - Wpf DataGrid 只显示空行

WPF ToolBar - 检测何时将项目设置到 ToolBarOverflowPanel 中

c# - 启动进程不适用于模拟

C# SqlConnection 连接字符串