温馨提示×

wpf怎么调用winform控件

wpf
小亿
221
2024-08-11 14:18:36
栏目: 智能运维
Windows服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在WPF中调用WinForms控件可以通过在WPF中使用WindowsFormsHost控件来实现。下面是一个简单的示例代码:

  1. 在XAML文件中添加WindowsFormsHost控件:
<Window x:Class="WpfApp.MainWindow"
        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="MainWindow" Height="450" Width="800">
    <Grid>
        <WindowsFormsHost Name="winFormsHost">
            <wf:Button Text="WinForms Button" Click="WinFormsButton_Click"/>
        </WindowsFormsHost>
    </Grid>
</Window>
  1. 在代码文件中处理WinForms控件的事件:
using System.Windows;
using System.Windows.Forms;

namespace WpfApp
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void WinFormsButton_Click(object sender, System.EventArgs e)
        {
            MessageBox.Show("Button Clicked");
        }
    }
}

这样就可以在WPF中调用WinForms控件,并处理其事件了。需要注意的是,WindowsFormsHost控件只能包含一个WinForms控件,如果需要多个WinForms控件,可以在WindowsFormsHost控件中嵌套一个Panel控件,然后将多个WinForms控件添加到Panel控件中。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:winform怎么调用wpf控件

1