在CAD中调用WPF窗口的几种方法(一)

1. 使用面板,将WPF用户控件嵌入面板

using Autodesk.AutoCAD.Windows;
using System;
using Palette = Autodesk.Windows.Palettes.Palette;

namespace ChangDiTools {
    class PalleteDemo {
        static PaletteSet ps;
        public static void DoIt()
        {
            if (ps == null)
            {
                ps = new PaletteSet("场地设计工具"
                    , new Guid("edd99713-4f36-4cfa-998b-88e50c9cd933"));
                ps.Style = PaletteSetStyles.ShowPropertiesMenu |
                           PaletteSetStyles.ShowAutoHideButton |
                           PaletteSetStyles.ShowCloseButton;
                ps.MinimumSize = new System.Drawing.Size(450, 250);
                Palette p1 = new Palette();
                p1.Content = new UserControl1();
                ps.AddVisual("场地设计工具", p1);
            }
            ps.Visible = true;
        }
    }
}
public class Command {
    [CommandMethod("ttt")]
    public static void Test()
    {
        PalleteDemo.DoIt();
    }
}

2. 在WinForm使用ElementHost

public MainWindow1()
{
    InitializeComponent();
    UserControl1 userControl1 = new UserControl1();
    elementHost1.Child = userControl1;
}

然后调用Winform窗口即可

public class Command {
    [CommandMethod("ttt")]
    public static void Test()
    {
        MainWindow1 mw=new MainWindow1();
        Application.Run(mw);
    }
}

最终效果如下:

3. 能否直接弹出WPF窗口?

在网上找了一篇老外的文章,翻译如下:

在Visual Studio中创建WPF项目并在AutoCAD2016中调用

要在Visual Studio中创建WPF项目,然后可以将其加载到AutoCAD中,则需要执行以下步骤:

1.创建项目:选择一个类库作为模板。

2.添加用户控件(WPF)

3.添加对xaml.dll的引用。这些和其他文件在计算机上,例如 C:\Program Files\Referenz Assemblies\Microsoft\Framework.NetFramework\v4.5.2\System.Xaml.dlll或.NetFrameworks其他子目录

4.添加对ComponentModell.dll的引用

5.添加对WindowsFormsIntegration.dll的引用

6.安装适用于AutoCAD的Nuget包(例如AutoCAD2016包)

7.添加Form1。

由于无法将WPF UserControl直接加载到AutoCAD中,因此必须将Windows Form添加到项目中,然后该窗体将充当WPF UserControl的承载者。必须将UserControl传递给表单(public Form1(UserControl1 myUserControl1))。然后在WinForms(ElementHost())中调用一个包含特殊WPF元素的宿主类。此类位于WindowsFormsIntegration.dll程序集中,项目必须知道该程序集。创建project.dll后,程序dll可以通过命令netload加载到AutoCAD中,并在这种情况下以命令“cb”启动。此命令通过[CommandMethod(“CB”)]在特殊类myAutoCAD命令中定义,因此可以在AutoCAD中进行寻址。

通过此过程,创建“框架”,然后创建实际程序。在WPF UserControl页面上,可以插入所有必要的附加控件,并对控件和AutoCAD API端的C#逻辑进行编程。然后将在此基础上创建此博客中的更多示例。

4. 结论

在CAD二次开发中,如果需要使用窗体,还是用Window Forms吧。如果需要做类似属性这样的面板再考虑使用WPF。