如何将WPF控件添加到WinForm中?

17

我知道必须使用ElementHost在WinForm中显示WPF控件,但由于WPF控件是第三方软件,只有一个XML文件和一个DLL文件。

该控件是AvalonEdit,我将ICSharpCode.AvalonEdit.xmlICSharpCode.AvalonEdit.dll文件添加到我的项目中,并转到Project -> Add Reference并将DLL添加为引用。现在我可以在我的代码中访问ICSharpCode命名空间,所有类和方法都已公开,但是从这一点我不确定如何在我的WinForm中实际使用该控件。

我原本期望在“解决资源管理器”中出现一个WPF控件,但事实上没有出现。 我尝试将ElementHost控件添加到我的WinForm中,但是当我尝试选择托管内容时,没有控件出现,因此它不知道我的WPF控件。 如何在我的WinForm中使用AvalonEdit WPF控件?


3
给那位给我的问题点了踩的人,如果您能留下评论告诉我为什么我的问题不好,那就太好了。 - Brandon Miller
3个回答

20

如果您希望能够在设计时设置托管内容,则控件需要成为您解决方案的一部分。实现这一目标的方法之一是创建一个包含您要使用的 AvalonEdit 组件的自定义 WPF 用户控件。例如:

  1. 创建一个 WPF 用户控件库项目并创建一个包含 AvalonEdit 组件的用户控件。

  2. 将用户控件项目添加到您的 Winforms 解决方案中。

现在,您应该能够选择您的新用户控件作为托管内容。

或者,您可以像这样直接在代码中添加 AvalonEdit 控件:

public Form1()
{
  InitializeComponent();

  ElementHost host= new ElementHost();
  host.Size = new Size(200, 100);
  host.Location = new Point(100,100);

  AvalonEditControl edit = new AvalonEditControl();
  host.Child = edit;

  this.Controls.Add(host);
}

不确定控件的名称,因此请根据需要替换AvalonEditControl。


2
控件的名称是AvalonEdit.TextEditor,我尝试了一下,它说无法转换为Control。我尝试了这个:TextEditor editor = new TextEditor(); elementHost1.Child = editor; this.Controls.Add((Control)editor); 为什么不能将其转换为控件? - Brandon Miller
4
this.Controls.Add((Control)editor)改为this.Controls.Add(elementHost1) - Tommy Grovnes
哦,我没注意到你添加了主机而不是控件本身。这样就可以了!非常感谢你! - Brandon Miller
非常抱歉,我本意是要这样做的。你的回答真是救了我一命。 - Brandon Miller

10

你可能想要一个如何进行代码着色/语法高��的示例:

public Form1()
{
    InitializeComponent();
    ICSharpCode.AvalonEdit.TextEditor textEditor = new ICSharpCode.AvalonEdit.TextEditor();
    textEditor.ShowLineNumbers = true;
    textEditor.FontFamily = new System.Windows.Media.FontFamily("Consolas");
    textEditor.FontSize = 12.75f;

    string dir = @"C:\Temp\";
    #if DEBUG
    dir = @"C:\Dev\Sandbox\SharpDevelop-master\src\Libraries\AvalonEdit\ICSharpCode.AvalonEdit\Highlighting\Resources\";
    #endif

    if (File.Exists(dir + "CSharp-Mode.xshd"))
    {
      Stream xshd_stream = File.OpenRead(dir + "CSharp-Mode.xshd");
      XmlTextReader xshd_reader = new XmlTextReader(xshd_stream);    
      // Apply the new syntax highlighting definition.
      textEditor.SyntaxHighlighting = ICSharpCode.AvalonEdit.Highlighting.Xshd.HighlightingLoader.Load(xshd_reader, ICSharpCode.AvalonEdit.Highlighting.HighlightingManager.Instance);
      xshd_reader.Close();
      xshd_stream.Close();
    }
    //Host the WPF AvalonEdiot control in a Winform ElementHost control
    ElementHost host = new ElementHost();
    host.Dock = DockStyle.Fill;
    host.Child = textEditor;
    this.Controls.Add(host);
}

0

this is result

        ElementHost host = new ElementHost();
        host.Size = new Size(200, 100);
        host.Location = new Point(100, 100);

        ICSharpCode.AvalonEdit.TextEditor edit = new 
        ICSharpCode.AvalonEdit.TextEditor();

        host.Child = edit;

        this.Controls.Add(host);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接