簡體   English   中英

C# WinForms Base UserControl

[英]C# WinForms Base UserControl

我在使用 UserControls 的 VS2019 中遇到了一些問題。

我有一個基本用戶控件 (WinForms),我希望從中繼承所有其他用戶控件。 基本控件提供了許多我需要的常用屬性。

public partial class MyBaseControl : System.Windows.Forms.UserControl
{

    internal Int32 _caseID;
    internal object _objectID;

    public int CaseID { get => _caseID; set => _caseID = value; }
    public object ObjectID { get => _objectID; set => _objectID = value; }

    internal virtual void MakeScreenReadOnly()
    {
    }
    public MyBaseControl()
    {
        Type systemType = this.GetType();
        PropertyInfo propertyInfo = systemType.GetProperty("DoubleBuffered", BindingFlags.Instance | BindingFlags.NonPublic);
        this.AutoScroll = true;

    }

}

繼承此基本控件的控件在應用程序運行時都可以正常工作,但我無法在設計器中查看該控件。 用戶控件是

public partial class AddressControl : MyBaseControl
    {
....
}

我得到錯誤

The service System.Windows.Forms.Design.IEventHandlerService already exists in the service container. Parameter name: serviceType

嘗試在設計器中查看 AddressControl 時。

這曾經在早期版本的 Visual Studio 中工作。 有沒有人有任何想法?

  • 從 Visual Studio 退出。
  • 打開文件資源管理器:導航到包含您的項目的文件夾。
  • 刪除“bin”和“obj”文件夾。
  • 再次打開 Visual Studio 並打開並重新編譯項目。

您可以嘗試重新創建用戶控件。

從項目中排除舊控件以將其保留在磁盤上。

將舊文件移出項目文件夾( MyBaseControl.csMyBaseControl.Designer.cs )。

使用Project > Add > User control向導。

將您的舊代碼復制到其中。

並且不要刪除InitializeComponent(); 從構造函數:之后添加您的代碼。

如果 Visual Studio 沒有損壞,它可能會起作用並解決您的問題,否則您可以嘗試修復或卸載並重新安裝它。

這是我嘗試過的:

  • 我添加了這個用戶控件:

     public partial class UserControl1: UserControl { public UserControl1() { InitializeComponent(); } }
  • 我編譯。

  • 我添加了另一個用戶控件並更改了父控件:

     public partial class UserControl2: UserControl1 { public UserControl2() { InitializeComponent(); } }

它工作正常,設計師正確顯示。

接下來,我在保持InitializeComponent()調用的同時添加了您的代碼:

public partial class UserControl1 : UserControl
{
  internal Int32 _caseID;
  internal object _objectID;

  public int CaseID { get => _caseID; set => _caseID = value; }
  public object ObjectID { get => _objectID; set => _objectID = value; }

  internal virtual void MakeScreenReadOnly()
  {
  }
  public UserControl1()
  {
    InitializeComponent();
    Type systemType = this.GetType();
    PropertyInfo propertyInfo = systemType.GetProperty("DoubleBuffered", BindingFlags.Instance | BindingFlags.NonPublic);
    this.AutoScroll = true;
  }
}

我編譯。

一切正常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM