xaml中承载Winform窗体控件

1、xaml不能直接承载winform窗体,可以承载usercontrol等控件

2、.net framework目前成功实现wpf中加载winform usercontrol控件,.net项目暂未能成功实现

3、.net framework实现关键步骤

3.1、添加引用

  • WindowsFormsIntegration

  • System.Windows.Forms

3.2实现xaml文件如下

<Window x:Class="HostingWfInWpfWithXamlNetFramework.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:HostingWfInWpfWithXamlNetFramework"
        xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
        xmlns:wfi="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <WindowsFormsHost Grid.Row="0">
            <wf:MaskedTextBox x:Name="mtbDate" Mask="00/00/0000"/>
        </WindowsFormsHost>
        <wfi:WindowsFormsHost Grid.Row="1" Name="winFormsHost1" Margin="10"/>
    </Grid>
</Window>

3.3界面对应cs文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Application = System.Windows.Application;

namespace HostingWfInWpfWithXamlNetFramework
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            Application.Current.Dispatcher.Invoke(() =>
            {
                winFormsHost1.Child = new Form1();
            });
        }
    }
}

3.4 Form1为自定义的一个UserControl

3.5参考微软官网例程https://learn.microsoft.com/zh-cn/previous-versions/dotnet/netframework-4.0/ms742875(v=vs.100)

posted @ 2026-04-01 09:57  echo-efun  阅读(4)  评论(0)    收藏  举报