WinformからWPFコントロールを呼び出す方法

WinForm と WPF は異なる UI 技術であり、お互いのコントロールを直接呼び出すことはできません。ただし、いくつかの方法で、それら間の相互作用を実現できます。次に一般的な方法を示します。

  1. WinFormにWPFコントロールをホストすることができるElementHostコントロールを追加する。
  2. WPF では呼び出す必要があるコントロールを作成し、グリッドやその他のコンテナーに配置します。
  3. ElementHost の Child プロパティに WPF のコントロール インスタンスを設定します。
  4. WinForm の ElementHost コントロールを通して WPF のコントロールにアクセスして操作する。

以下にサンプルコードを示します。

WinFormにおいて:

using System.Windows.Forms;
using System.Windows.Forms.Integration;
namespace WinFormWpfInterop
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
// 创建WPF的控件实例
var wpfControl = new WpfControl();
// 创建ElementHost控件
var elementHost = new ElementHost
{
Dock = DockStyle.Fill,
Child = wpfControl
};
// 将ElementHost添加到WinForm的Controls集合中
Controls.Add(elementHost);
}
}
}

WPFでは、

<UserControl x:Class="WinFormWpfInterop.WpfControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<Button Content="WPF Button" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
</UserControl>

これによりWinFormではElementHostコントロールによってWPF内のコントロールへのアクセスと操作が可能になる。

bannerAds