如何在NET 6.0中编写WinForms设计器

wqnecbli  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(167)

我需要创建WinForms项目下的组件。NET库版本6.0。但是,当我创建项目和ControlLibrary时,Visual Studio窗体设计器并不使用ControlLibrary中的ControlDesigners,即使我正确地将设计器绑定到组件。

[Designer(typeof(MyControlDesigner))]
  [ToolboxItem(true)]
  public class MyControl : Control 
  {

    protected override void OnPaint(PaintEventArgs e)
    {
      e.Graphics.FillRectangle(SystemBrushes.Info, new Rectangle(0, 0, Width, Height));
      e.Graphics.DrawString("MyControl", Font, SystemBrushes.InfoText, new PointF(0, 0));
    }
  }

我已经创建了一些ActionList,但它们在设计时没有显示在组件中。

namespace WinFormsControlLibrary1
{
  internal class MyControlDesigner : ControlDesigner
  {
    private DesignerActionListCollection actionLists;

    public override DesignerActionListCollection ActionLists
    {
      get
      {
        if (actionLists == null)
        {
          actionLists = new DesignerActionListCollection();
          actionLists.Add(new DataAxisGridActionList(Component));
          actionLists.AddRange(base.ActionLists);
        }
        return actionLists;
      }
    }
  }

  public class DataAxisGridActionList : DesignerActionList
  {

    public DataAxisGridActionList(IComponent component) : base(component)
    {
    }

    public override DesignerActionItemCollection GetSortedActionItems()
    {
      DesignerActionItemCollection items = new DesignerActionItemCollection();
      items.Add(new DesignerActionMethodItem(this, "Action1", " Action 1", true));
      items.Add(new DesignerActionMethodItem(this, "Action2", "Action 2", true));
      return items;
    }

    public void Action1()
    {
      MessageBox.Show("Action 1");
    }

    public void Action2()
    {
      MessageBox.Show("Action 2");
    }
  }

}

为了测试,我在.NET Framework 4.7.2下创建了一个类似的项目和库,设计器在那里正常工作。

我还附上一个链接到演示项目。
https://github.com/dmitrybv/WinForms-Net5-Designers
https://github.com/dmitrybv/WinForms-Net-Framework-4.7.2-Designers

gdx19jrr

gdx19jrr1#

目前,由于WinForms Designer的新进程外体系结构中的设计时支持尚未完全完成,可能更简单的解决方案是安装WinForms Designer Extensibility SDK。
它可以通过NuGet包管理器获得,使用名称:Microsoft.WinForms.Designer.SDK
或在包管理器控制台中粘贴:

NuGet\Install-Package Microsoft.WinForms.Designer.SDK -Version 1.6.0

或将Package Reference添加到<PackageReference>的现有<ItemGroup>中的项目配置文件中(或创建一个新文件):

<PackageReference Include="Microsoft.WinForms.Designer.SDK" Version="1.6.0" />

有关Designer支持的当前状态的说明,请参见此处:
State of the Windows Forms Designer for .NET Applications
在包含自定义设计器(ControlDesignerDocumentDesigner支持)的代码文件中添加所需的using指令:

using Microsoft.DotNet.DesignTools.Designers;

对于可以接收命中测试和绘制消息的行为服务和装饰器(字形):

using Microsoft.DotNet.DesignTools.Designers.Behaviors

相关问题