【问题标题】:How can I easily replace one control for another with the same name in Windows Forms?如何在 Windows 窗体中轻松地将一个控件替换为另一个具有相同名称的控件?
【发布时间】:2016-02-28 20:24:13
【问题描述】:

第一个问题是在form1 top 我有:

ListViewNF lvnf;

ListViewNF 是form1 中的一个类:

class ListViewNF : System.Windows.Forms.ListView
        {
            public ListViewNF()
            {
                //Activate double buffering
                this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);

                //Enable the OnNotifyMessage event so we get a chance to filter out 
                // Windows messages before they get to the form's WndProc
                this.SetStyle(ControlStyles.EnableNotifyMessage, true);
            }

            protected override void OnNotifyMessage(System.Windows.Forms.Message m)
            {
                if (m.Msg != 0x14)
                {
                    base.OnNotifyMessage(m);
                }
            }
        }

然后在 form1 构造函数中,我为lvnf 变量设置大小、位置并将此控件lvnf 添加到form1 控件中。 然后在我的程序中,我在某些地方使用了lvnf。

但现在我想创建一个新的UserControl,将其命名为lvnf,因此当我将UserControl 从工具箱拖到form1 设计器时,它将替换我创建的lvnf。

第一个问题是一旦我删除该行:

ListViewNF lvnf;

我遇到很多错误,看不到 form1 设计器 我遇到了一个错误,因为lvnf 不存在。

如果我不删除它并拖动新的UserControl,它将给新控件另一个名称,我希望它是lvnf。我不想更改与lvnf 相关的运行时代码中的任何内容,只更改设计器中的控件。

这是UserControl的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Pop3_Emails
{
    public partial class ListViewNF : UserControl
    {
        public ListViewNF()
        {
            InitializeComponent();           
        }
    }
}

我是否应该将lvnf 的所有事件移动到UserControl 代码中?还是全部留在form1?

主要问题是如何将UserControl 用作lvnf。 另外我需要使用ListViewNF类中的代码。

真是一团糟。一般来说,我想要做的是使lvnf ListViewNF 成为form1 设计器中的控件,而不是运行时代码中的控件。

【问题讨论】:

    标签: c# .net winforms


    【解决方案1】:
    1. 将新的UserControl 拖到表单上,使用不同的名称(例如x)
    2. 将lvnf 重命名为x,要求Visual Studio 更新所有引用。忽略名称已存在的警告,项目将无法编译。
    3. 删除ListViewNF x 声明(现在项目应该再次编译)。
    4. 将x 重命名为lvnf,同时更新所有引用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多