簡體   English   中英

如何在WPF應用程序中放置自定義Windows窗體控件?

[英]How to put a custom windows forms control in a WPF application?

作為一個短期解決方案,我試圖將Windows表單'usercontrol'阻塞到WPF應用程序中。 我在WPF應用程序視圖中看到我可以向項目添加一個“自定義窗體控件”,它會生成一個空的自定義控件,但我無法弄清楚如何添加它。 理想情況下,我想知道如何從我編譯的Windows窗體用戶控件中獲取.dll並將其粘貼到WPF應用程序中,或將用戶控件導入WPF應用程序。

謝謝,山姆

您無法像在Windows窗體應用程序中那樣將其作為控件添加到工具箱中。 你應該做的是“托管”WPF應用程序內部的用戶控件。

了解如何在MSDN上執行此操作

以下是如何使用蒙版文本框(您可以輕松修改以使用自定義控件)的示例:

<Window x:Class="Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"  
Title="HostingWfInWpf">
<Grid>
    <WindowsFormsHost>
       <wf:MaskedTextBox x:Name="mtbDate" Mask="00/00/0000"/>
    </WindowsFormsHost>
</Grid>
</Window>

將System.Windows.Forms和WindowsFormsIntegration的引用添加到項目中

xmlns:WinForms="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
xmlns:WindowsFormsIntegration="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"

並將Windows窗體主機放在窗口中。

  <WindowsFormsHost Name="wfhDate"  
                    HorizontalAlignment="Center" 
                    VerticalAlignment="Stretch">
                <WinForms:FlowLayoutPanel/>
  </WindowsFormsHost>

現在用C#代碼

using Forms = System.Windows.Forms;
.........................
Forms.FlowLayoutPanel flpPanel = this.wfhDate.Child as Forms.FlowLayoutPanel;
// Initialize your Forms contol here.
flpPanel.Controls.Add( yourControl );

盧卡斯的回答是正確的,但我想補充一些必要的東西。 如果要創建Web應用程序,則必須將“安全性”設置更改為“這是完全信任的應用程序”。 在執行此操作之前,我無法使WindowsFormsHost控件正常工作。

暫無
暫無

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

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