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

血红的双手。 提交于 2019-12-30 03:26:09

问题


As a short term solution I'm trying to jam a windows form 'usercontrol' into a WPF application. I see in the WPF application view that I can add a 'custom windows form control' to the project and it makes an empty custom control, but I can't figure out how to add it. Ideally I'd like to know how to take the .dll from my compiled windows forms user control and stick it into the WPF app, or import the user control into the WPF application.

Thanks, Sam


回答1:


You can't really add it as a control to the toolbox like you could for a Windows Forms Application. What you should do instead is "host" the user control inside of the WPF application.

See how to do it on MSDN.

Here's an example of how to use a masked text box (which you can easily modify to use your custom control):

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



回答2:


Add a reference to System.Windows.Forms and WindowsFormsIntegration to your Project

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

And place Windows forms host in the window.

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

Now in C# code

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



回答3:


Lucas' answer is correct, but I wanted to add something needed. If you are creating a web application, then you must change the Security setting to This is a full trust application. I could not get the WindowsFormsHost control to work prior to doing this.



来源:https://stackoverflow.com/questions/1310154/how-to-put-a-custom-windows-forms-control-in-a-wpf-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!