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

前端 未结 3 1256
不思量自难忘°
不思量自难忘° 2021-01-01 02:18

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

相关标签:
3条回答
  • 2021-01-01 02:26

    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>
    
    0 讨论(0)
  • 2021-01-01 02:33

    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 );
    
    0 讨论(0)
  • 2021-01-01 02:34

    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.

    0 讨论(0)
提交回复
热议问题