簡體   English   中英

如何將此 WPF 控件添加到我的 WinForm 中?

[英]How can I add this WPF control into my WinForm?

我知道我必須使用ElementHost在 WinForm 中顯示 WPF 控件,但由於 WPF 控件是第三方軟件,它只附帶一個 XML 文件和一個 DLL 文件。

控件是AvalonEdit ,我將ICSharpCode.AvalonEdit.xmlICSharpCode.AvalonEdit.dll文件都添加到我的項目中,然后我轉到Project -> Add Reference並添加了 DLL 作為參考。 現在我可以在我的代碼中訪問ICSharpCode命名空間,所有的類和方法都公開了,但從這一點來看,我不確定如何在我的 WinForm 中實際使用該控件。

我期待 WPF 控件出現在解決方案資源管理器中,但它沒有。 無論如何,我嘗試向我的 WinForm 添加一個ElementHost控件,但是當我嘗試選擇托管內容時,沒有出現任何控件,因此它不知道我的 WPF 控件。 如何在我的 WinForm 中使用 AvalonEdit WPF 控件?

如果您希望能夠在設計時設置托管內容,則控件需要成為解決方案的一部分。 實現這一目標的一種方法是創建一個自定義 WPF 用戶控件,其中包含您要使用的 AvalonEdit 組件。 IE

  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。

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);
}

這是結果

        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);

暫無
暫無

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

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