在WPF中調用WinForms控件可以通過在WPF中使用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>
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控件中。