更新 : 2007 年 11 月
Windows Presentation Foundation (WPF) は、アプリケーションの作成に適した環境を提供します。ただし、Windows フォームのコードに多くの投資を行った場合は、コードを最初から記述し直すよりも、WPF アプリケーションのコードの少なくとも一部を再利用する方が効率的です。最も一般的なシナリオは、既存のカスタム Windows フォーム コントロールがある場合です。場合によっては、これらのコントロールのソース コードにアクセスできないことがあります。WPF には、そのようなコントロールを WPF アプリケーションでホストするための簡単な手順が用意されています。たとえば、特殊な System.Windows.Forms.DataGridView コントロールをホストしながら、ほとんどのプログラミングには WPF を使用できます。
このチュートリアルでは、WPF ページで複合 Windows フォーム コントロールをホストするアプリケーションについて段階的に説明します。この一般的な手順は、さらに複雑なアプリケーションやコントロールに拡張できます。
チュートリアルは、2 つのセクションに分かれています。最初のセクションでは、Windows フォーム コントロールの実装について簡単に説明します。2 番目のセクションでは、WPF アプリケーションでコントロールをホストし、コントロールからイベントを受け取って、コントロールのプロパティの一部にアクセスする方法について詳しく説明します。
このチュートリアルでは、以下のタスクを行います。
Windows フォーム コントロールを実装する。
Windows Presentation Foundation でホスト アプリケーションを実装する。
このチュートリアルで示すタスクの完全なコード一覧については、「Windows Presentation Foundation での Windows フォーム複合コントロールのホストのサンプル」を参照してください。
必要条件
このチュートリアルを完了するには、次のコンポーネントが必要です。
- Visual Studio 2008.
Windows フォーム コントロールの実装
この例で使用する Windows フォーム コントロールは、単純なデータ入力フォームです。このフォームは、ユーザーの名前と住所を受け取った後、カスタム イベントを使用してその情報をホストに返します。レンダリングされたコントロールを次の図に示します。
Windows フォーム コントロール
プロジェクトの作成
プロジェクトを開始するには
Microsoft Visual Studio を起動して、[新しいプロジェクト] ダイアログ ボックスを開きます。
[C# プロジェクト] を選択し、[Windows フォーム コントロール ライブラリ] テンプレートを選択します。
新しいプロジェクトに MyControls という名前を設定し、[OK] をクリックしてプロジェクトを作成します。既定のプロジェクトには、UserControl1 という名前の 1 つのコントロールが含まれます。
このコントロールの名前を、UserControl1 から MyControl1 に変更します。
プロジェクトは、次のシステム DLL を参照している必要があります。これらの DLL のいずれかが既定で含まれていない場合は、プロジェクトに追加します。
System
System.Data
System.Drawing
System.Windows.Forms
System.XML
フォームへのコントロールの追加
フォームにコントロールを追加するには、次の操作を実行します。
- MyControl1 のデザイナを開きます。
6 つの System.Windows.Forms.Label コントロールとそれに対応する System.Windows.Forms.TextBox コントロールを、前の図と同じようなサイズと位置関係で、フォーム上に配置します。この例では、TextBox コントロールには次のような名前を付けます。
txtName
txtAddress
txtCity
txtState
txtZip
OK と Cancel というラベルを付けた 2 つの System.Windows.Forms.Button コントロールを追加します。この例では、ボタンの名前はそれぞれ btnOK と btnCancel です。
サポート コードの実装
フォームのコード ビューを開きます。コントロールは、カスタム OnButtonClick イベントを発生させることで、収集したデータをホストに返します。データは、イベント引数オブジェクトに格納されています。次のコード例では、イベントとデリゲートの宣言を示します。コード ファイルの、デザイナによって生成されたコードの下に、このコードを追加します。
Public Delegate Sub MyControlEventHandler(ByVal sender As Object, ByVal args As MyControlEventArgs)
Public Event OnButtonClick As MyControlEventHandler
public delegate void MyControlEventHandler(object sender, MyControlEventArgs args);
public event MyControlEventHandler OnButtonClick;
MyControlEventArgs クラスには、ホストに返される情報が格納されます。次のクラスをフォームの名前空間に追加します。
Public Class MyControlEventArgs
Inherits EventArgs
Private _Name As String
Private _StreetAddress As String
Private _City As String
Private _State As String
Private _Zip As String
Private _IsOK As Boolean
Public Sub New(ByVal result As Boolean, ByVal name As String, ByVal address As String, ByVal city As String, ByVal state As String, ByVal zip As String)
_IsOK = result
_Name = name
_StreetAddress = address
_City = city
_State = state
_Zip = zip
End Sub
Public Property MyName() As String
Get
Return _Name
End Get
Set
_Name = value
End Set
End Property
Public Property MyStreetAddress() As String
Get
Return _StreetAddress
End Get
Set
_StreetAddress = value
End Set
End Property
Public Property MyCity() As String
Get
Return _City
End Get
Set
_City = value
End Set
End Property
Public Property MyState() As String
Get
Return _State
End Get
Set
_State = value
End Set
End Property
Public Property MyZip() As String
Get
Return _Zip
End Get
Set
_Zip = value
End Set
End Property
Public Property IsOK() As Boolean
Get
Return _IsOK
End Get
Set
_IsOK = value
End Set
End Property
End Class
public class MyControlEventArgs : EventArgs
{
private string _Name;
private string _StreetAddress;
private string _City;
private string _State;
private string _Zip;
private bool _IsOK;
public MyControlEventArgs(bool result,
string name,
string address,
string city,
string state,
string zip)
{
_IsOK = result;
_Name = name;
_StreetAddress = address;
_City = city;
_State = state;
_Zip = zip;
}
public string MyName
{
get { return _Name; }
set { _Name = value; }
}
public string MyStreetAddress
{
get { return _StreetAddress; }
set { _StreetAddress = value; }
}
public string MyCity
{
get { return _City; }
set { _City = value; }
}
public string MyState
{
get { return _State; }
set { _State = value; }
}
public string MyZip
{
get { return _Zip; }
set { _Zip = value; }
}
public bool IsOK
{
get { return _IsOK; }
set { _IsOK = value; }
}
}
ユーザーが [OK] ボタンまたは [Cancel] ボタンをクリックすると、Control.Click イベント ハンドラはデータを格納した MyControlEventArgs オブジェクトを作成し、OnButtonClick イベントを発生させます。2 つのハンドラの違いは、イベント引数の IsOK プロパティだけです。このプロパティにより、ホストはどちらのボタンがクリックされたのかを判別できます。[OK] ボタンの場合は true が設定され、[Cancel] ボタンの場合は false が設定されます。次のコード例では、2 つのボタン ハンドラを示します。クラスにこのコードを追加し、このセクションの最初のコード例で示されているイベントとデリゲートの宣言の下に配置します。
Private Sub OKButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnOK.Click
Dim retvals As New MyControlEventArgs(True, txtName.Text, txtAddress.Text, txtCity.Text, txtState.Text, txtZip.Text)
RaiseEvent OnButtonClick(Me, retvals)
End Sub
Private Sub CancelButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
Dim retvals As New MyControlEventArgs(False, txtName.Text, txtAddress.Text, txtCity.Text, txtState.Text, txtZip.Text)
RaiseEvent OnButtonClick(Me, retvals)
End Sub
End Class
private void OKButton_Click(object sender, System.EventArgs e)
{
MyControlEventArgs retvals = new MyControlEventArgs(true,
txtName.Text,
txtAddress.Text,
txtCity.Text,
txtState.Text,
txtZip.Text);
OnButtonClick(this, retvals);
}
private void CancelButton_Click(object sender, System.EventArgs e)
{
MyControlEventArgs retvals = new MyControlEventArgs(false,
txtName.Text,
txtAddress.Text,
txtCity.Text,
txtState.Text,
txtZip.Text);
OnButtonClick(this, retvals);
}
アセンブリへの厳密な名前の設定とアセンブリのビルド
WPF アプリケーションからこのアセンブリを参照するには、アセンブリに厳密な名前を付ける必要があります。厳密な名前を作成するには、Sn.exe でキー ファイルを作成し、それをプロジェクトの AssemblyInfo.cs ファイルに追加します。
Visual Studio のコマンド プロンプトを開きます。この操作を行うには、[スタート] メニューから [すべてのプログラム]、[Microsoft Visual Studio 2008]、[Visual Studio ツール] の順にポイントし、[Visual Studio 2008 コマンド プロンプト] をクリックします。カスタマイズされた環境変数でコンソール ウィンドウが起動されます。
コマンド プロンプトで、"cd" コマンドを使用してプロジェクト フォルダに移動します。
次のコマンドを実行し、MyControls.snk という名前のキー ファイルを生成します。
Sn.exe -k MyControls.snk
キー ファイルをプロジェクトに組み込むには、ソリューション エクスプローラでプロジェクト名を右クリックし、[プロパティ] ダイアログ ボックスを開きます。[署名] タブをクリックし、キー ファイルの名前を入力します。
アセンブリをビルドします。ビルドでは、MyControls.dll という名前の DLL が生成されます。
Windows Presentation Foundation によるホスト アプリケーションの実装
WPF ホスト アプリケーションは、WindowsFormsHost コントロールを使用して MyControl1 をホストします。アプリケーションは、OnButtonClick イベントを処理して、コントロールからデータを受け取ります。また、WPF ページからコントロールの一部のプロパティを変更できるオプション ボタンのコレクションもあります。最終的なアプリケーションを次の図に示します。
Windows Presentation Foundation ページに埋め込まれたコントロールが表示されている完成したアプリケーション
プロジェクトの作成
プロジェクトを開始するには
Visual Studio を開き、[新しいプロジェクト] を選択します。
[WPF ブラウザ アプリケーション] テンプレートを選択します。
プロジェクトに WpfHost という名前を設定し、[OK] をクリックしてプロジェクトを開きます。
MyControl1 を含む DLL への参照も追加する必要があります。参照を追加する最も簡単な方法は次のとおりです。
ソリューション エクスプローラでプロジェクト名を右クリックし、[参照の追加] ダイアログ ボックスを開きます。
[参照] タブをクリックし、Windows フォーム コントロールの出力フォルダを参照します。このサンプルの場合は、MyControls\bin\Debug フォルダです。
コントロールを含む DLL を選択し、[OK] をクリックして参照の一覧に追加します。「Windows Presentation Foundation での Windows フォーム複合コントロールのホストのサンプル」では、この DLL は MyControls.dll という名前です。
ソリューション エクスプローラで、WindowsFormsIntegration.dll という名前の WindowsFormsIntegration アセンブリへの参照を追加します。
基本レイアウトの実装
ホスト アプリケーションのユーザー インターフェイス (UI) は、Page1.xaml で実装されます。このファイルは、ページ レイアウトを定義する Extensible Application Markup Language (XAML) マークアップを含み、Windows フォーム コントロールをホストします。ページは次の 3 つの領域に分かれています。
[Control Properties] パネルには、ホストされるコントロールのさまざまなプロパティの変更に使用できるオプション ボタンのコレクションが含まれます。
[Data from Control] パネルには、ホストされるコントロールから返されるデータを表示する TextBlock 要素が含まれます。
ホストされるコントロール自体。
基本的なレイアウト コードを次のコード例に示します。MyControl1 をホストするために必要なマークアップ コードはこの例では省略されていますが、これについては後で説明します。Page1.xaml 内のコードを次のコードに置き換えます。
<Page xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
x:Class="Page1"
xmlns:mcl="clr-namespace:MyControls;assembly=MyControls"
Loaded="Init">
<DockPanel>
<DockPanel.Resources>
<Style x:Key="inlineText" TargetType="{x:Type Inline}">
<Setter Property="FontWeight" Value="Normal"/>
</Style>
<Style x:Key="titleText" TargetType="{x:Type TextBlock}">
<Setter Property="DockPanel.Dock" Value="Top"/>
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="Margin" Value="10,5,10,0"/>
</Style>
</DockPanel.Resources>
<StackPanel Orientation="Vertical"
DockPanel.Dock="Left"
Background="Bisque"
Width="250">
<TextBlock Margin="10,10,10,10"
FontWeight="Bold"
FontSize="12">Control Properties</TextBlock>
<TextBlock Style="{StaticResource titleText}">Background Color</TextBlock>
<StackPanel Margin="10,10,10,10">
<RadioButton Name="rdbtnOriginalBackColor"
IsChecked="True"
Click="BackColorChanged">Original</RadioButton>
<RadioButton Name="rdbtnBackGreen"
Click="BackColorChanged">LightGreen</RadioButton>
<RadioButton Name="rdbtnBackSalmon"
Click="BackColorChanged">LightSalmon</RadioButton>
</StackPanel>
<TextBlock Style="{StaticResource titleText}">Foreground Color</TextBlock>
<StackPanel Margin="10,10,10,10">
<RadioButton Name="rdbtnOriginalForeColor"
IsChecked="True"
Click="ForeColorChanged">Original</RadioButton>
<RadioButton Name="rdbtnForeRed"
Click="ForeColorChanged">Red</RadioButton>
<RadioButton Name="rdbtnForeYellow"
Click="ForeColorChanged">Yellow</RadioButton>
</StackPanel>
<TextBlock Style="{StaticResource titleText}">Font Family</TextBlock>
<StackPanel Margin="10,10,10,10">
<RadioButton Name="rdbtnOriginalFamily"
IsChecked="True"
Click="FontChanged">Original</RadioButton>
<RadioButton Name="rdbtnTimes"
Click="FontChanged">Times New Roman</RadioButton>
<RadioButton Name="rdbtnWingdings"
Click="FontChanged">Wingdings</RadioButton>
</StackPanel>
<TextBlock Style="{StaticResource titleText}">Font Size</TextBlock>
<StackPanel Margin="10,10,10,10">
<RadioButton Name="rdbtnOriginalSize"
IsChecked="True"
Click="FontSizeChanged">Original</RadioButton>
<RadioButton Name="rdbtnTen"
Click="FontSizeChanged">10</RadioButton>
<RadioButton Name="rdbtnTwelve"
Click="FontSizeChanged">12</RadioButton>
</StackPanel>
<TextBlock Style="{StaticResource titleText}">Font Style</TextBlock>
<StackPanel Margin="10,10,10,10">
<RadioButton Name="rdbtnNormalStyle"
IsChecked="True"
Click="StyleChanged">Original</RadioButton>
<RadioButton Name="rdbtnItalic"
Click="StyleChanged">Italic</RadioButton>
</StackPanel>
<TextBlock Style="{StaticResource titleText}">Font Weight</TextBlock>
<StackPanel Margin="10,10,10,10">
<RadioButton Name="rdbtnOriginalWeight"
IsChecked="True"
Click="WeightChanged">
Original
</RadioButton>
<RadioButton Name="rdbtnBold"
Click="WeightChanged">Bold</RadioButton>
</StackPanel>
</StackPanel>
<WindowsFormsHost Name="wfh"
DockPanel.Dock="Top"
Height="300">
<mcl:MyControl1 Name="mc"/>
</WindowsFormsHost>
<StackPanel Orientation="Vertical"
Height="Auto"
Background="LightBlue">
<TextBlock Margin="10,10,10,10"
FontWeight="Bold"
FontSize="12">Data From Control</TextBlock>
<TextBlock Style="{StaticResource titleText}">
Name: <Span Name="txtName" Style="{StaticResource inlineText}"/>
</TextBlock>
<TextBlock Style="{StaticResource titleText}">
Street Address: <Span Name="txtAddress" Style="{StaticResource inlineText}"/>
</TextBlock>
<TextBlock Style="{StaticResource titleText}">
City: <Span Name="txtCity" Style="{StaticResource inlineText}"/>
</TextBlock>
<TextBlock Style="{StaticResource titleText}">
State: <Span Name="txtState" Style="{StaticResource inlineText}"/>
</TextBlock>
<TextBlock Style="{StaticResource titleText}">
Zip: <Span Name="txtZip" Style="{StaticResource inlineText}"/>
</TextBlock>
</StackPanel>
</DockPanel>
</Page>
<Page xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
x:Class="WpfHost.Page1"
xmlns:mcl="clr-namespace:MyControls;assembly=MyControls"
Loaded="Init">
<DockPanel>
<DockPanel.Resources>
<Style x:Key="inlineText" TargetType="{x:Type Inline}">
<Setter Property="FontWeight" Value="Normal"/>
</Style>
<Style x:Key="titleText" TargetType="{x:Type TextBlock}">
<Setter Property="DockPanel.Dock" Value="Top"/>
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="Margin" Value="10,5,10,0"/>
</Style>
</DockPanel.Resources>
<StackPanel Orientation="Vertical"
DockPanel.Dock="Left"
Background="Bisque"
Width="250">
<TextBlock Margin="10,10,10,10"
FontWeight="Bold"
FontSize="12">Control Properties</TextBlock>
<TextBlock Style="{StaticResource titleText}">Background Color</TextBlock>
<StackPanel Margin="10,10,10,10">
<RadioButton Name="rdbtnOriginalBackColor"
IsChecked="True"
Click="BackColorChanged">Original</RadioButton>
<RadioButton Name="rdbtnBackGreen"
Click="BackColorChanged">LightGreen</RadioButton>
<RadioButton Name="rdbtnBackSalmon"
Click="BackColorChanged">LightSalmon</RadioButton>
</StackPanel>
<TextBlock Style="{StaticResource titleText}">Foreground Color</TextBlock>
<StackPanel Margin="10,10,10,10">
<RadioButton Name="rdbtnOriginalForeColor"
IsChecked="True"
Click="ForeColorChanged">Original</RadioButton>
<RadioButton Name="rdbtnForeRed"
Click="ForeColorChanged">Red</RadioButton>
<RadioButton Name="rdbtnForeYellow"
Click="ForeColorChanged">Yellow</RadioButton>
</StackPanel>
<TextBlock Style="{StaticResource titleText}">Font Family</TextBlock>
<StackPanel Margin="10,10,10,10">
<RadioButton Name="rdbtnOriginalFamily"
IsChecked="True"
Click="FontChanged">Original</RadioButton>
<RadioButton Name="rdbtnTimes"
Click="FontChanged">Times New Roman</RadioButton>
<RadioButton Name="rdbtnWingdings"
Click="FontChanged">Wingdings</RadioButton>
</StackPanel>
<TextBlock Style="{StaticResource titleText}">Font Size</TextBlock>
<StackPanel Margin="10,10,10,10">
<RadioButton Name="rdbtnOriginalSize"
IsChecked="True"
Click="FontSizeChanged">Original</RadioButton>
<RadioButton Name="rdbtnTen"
Click="FontSizeChanged">10</RadioButton>
<RadioButton Name="rdbtnTwelve"
Click="FontSizeChanged">12</RadioButton>
</StackPanel>
<TextBlock Style="{StaticResource titleText}">Font Style</TextBlock>
<StackPanel Margin="10,10,10,10">
<RadioButton Name="rdbtnNormalStyle"
IsChecked="True"
Click="StyleChanged">Original</RadioButton>
<RadioButton Name="rdbtnItalic"
Click="StyleChanged">Italic</RadioButton>
</StackPanel>
<TextBlock Style="{StaticResource titleText}">Font Weight</TextBlock>
<StackPanel Margin="10,10,10,10">
<RadioButton Name="rdbtnOriginalWeight"
IsChecked="True"
Click="WeightChanged">
Original
</RadioButton>
<RadioButton Name="rdbtnBold"
Click="WeightChanged">Bold</RadioButton>
</StackPanel>
</StackPanel>
<WindowsFormsHost Name="wfh"
DockPanel.Dock="Top"
Height="300">
<mcl:MyControl1 Name="mc"/>
</WindowsFormsHost>
<StackPanel Orientation="Vertical"
Height="Auto"
Background="LightBlue">
<TextBlock Margin="10,10,10,10"
FontWeight="Bold"
FontSize="12">Data From Control</TextBlock>
<TextBlock Style="{StaticResource titleText}">
Name: <Span Name="txtName" Style="{StaticResource inlineText}"/>
</TextBlock>
<TextBlock Style="{StaticResource titleText}">
Street Address: <Span Name="txtAddress" Style="{StaticResource inlineText}"/>
</TextBlock>
<TextBlock Style="{StaticResource titleText}">
City: <Span Name="txtCity" Style="{StaticResource inlineText}"/>
</TextBlock>
<TextBlock Style="{StaticResource titleText}">
State: <Span Name="txtState" Style="{StaticResource inlineText}"/>
</TextBlock>
<TextBlock Style="{StaticResource titleText}">
Zip: <Span Name="txtZip" Style="{StaticResource inlineText}"/>
</TextBlock>
</StackPanel>
</DockPanel>
</Page>
最初の StackPanel 要素には、ホストされるコントロールのさまざまな既定のプロパティを変更できる一連の RadioButton コントロールが含まれます。その後にある WindowsFormsHost 要素は、MyControl1 をホストします。最後の StackPanel 要素には、ホストされるコントロールから返されるデータを表示する TextBlock 要素が含まれます。要素の順序、および Dock 属性と Height 属性の設定により、すきまやゆがみがないように、ホストされるコントロールがページに埋め込まれます。
コントロールのホスト
次のコードは前のコード例を編集したものですが、ここでは MyControl1 をホストするために必要な要素に焦点を当てます。
<Page xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
x:Class="Page1"
xmlns:mcl="clr-namespace:MyControls;assembly=MyControls"
Loaded="Init">
...
<WindowsFormsHost Name="wfh"
DockPanel.Dock="Top"
Height="300">
<mcl:MyControl1 Name="mc"/>
</WindowsFormsHost>
<Page xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
x:Class="WpfHost.Page1"
xmlns:mcl="clr-namespace:MyControls;assembly=MyControls"
Loaded="Init">
...
<WindowsFormsHost Name="wfh"
DockPanel.Dock="Top"
Height="300">
<mcl:MyControl1 Name="mc"/>
</WindowsFormsHost>
xmlns 名前空間の割り当ての属性により、ホストされるコントロールを格納する MyControls 名前空間への参照が作成されます。この割り当てにより、XAML で MyControl1 を <mcl:MyControl1> として表すことができます。
コード例に含まれる次の 2 つの要素がホストを処理します。
WindowsFormsHost は、WPF ページでの Windows フォーム コントロールのホストを可能にする WindowsFormsHost 要素を表します。
MyControl1 を表す mcl:MyControl1 は、WindowsFormsHost 要素の子コレクションに追加されます。結果として、この Windows フォーム コントロールは WPF ページの一部としてレンダリングされ、ページからコントロールと通信できます。
分離コード ファイルの実装
分離コード ファイル Page1.xaml.cs には、前のセクションで説明した UI の機能を実装する手順コードが含まれます。主要なタスクは次のとおりです。
MyControl1 の OnButtonClick イベントへのイベント ハンドラのアタッチ。
一連のオプション ボタンの設定に基づく、MyControl1 のさまざまなプロパティの変更。
コントロールによって収集されたデータの表示。
アプリケーションの初期化
初期化コードは、ページの Loaded イベントのイベント ハンドラに含まれ、イベント ハンドラをコントロールの OnButtonClick イベントにアタッチします。次のコードを、Page1.xaml.cs の Page1 クラスにコピーします。
Class Page1
Inherits Page
Private app As Application
Private myWindow As NavigationWindow
Private initFontWeight As FontWeight
Private initFontSize As [Double]
Private initFontStyle As FontStyle
Private initBackBrush As SolidColorBrush
Private initForeBrush As SolidColorBrush
Private initFontFamily As FontFamily
Private UIIsReady As Boolean = False
Private Sub Init(ByVal sender As Object, ByVal e As RoutedEventArgs)
app = System.Windows.Application.Current
myWindow = CType(app.MainWindow, NavigationWindow)
myWindow.SizeToContent = SizeToContent.WidthAndHeight
wfh.TabIndex = 10
initFontSize = wfh.FontSize
initFontWeight = wfh.FontWeight
initFontFamily = wfh.FontFamily
initFontStyle = wfh.FontStyle
initBackBrush = CType(wfh.Background, SolidColorBrush)
initForeBrush = CType(wfh.Foreground, SolidColorBrush)
Dim mc As MyControl1 = wfh.Child
AddHandler mc.OnButtonClick, AddressOf Pane1_OnButtonClick
UIIsReady = True
End Sub
public partial class Page1 : Page
{
private Application app;
private NavigationWindow myWindow;
FontWeight initFontWeight;
Double initFontSize;
FontStyle initFontStyle;
SolidColorBrush initBackBrush;
SolidColorBrush initForeBrush;
FontFamily initFontFamily;
bool UIIsReady = false;
private void Init(object sender, EventArgs e)
{
app = System.Windows.Application.Current;
myWindow = (NavigationWindow)app.MainWindow;
myWindow.SizeToContent = SizeToContent.WidthAndHeight;
wfh.TabIndex = 10;
initFontSize = wfh.FontSize;
initFontWeight = wfh.FontWeight;
initFontFamily = wfh.FontFamily;
initFontStyle = wfh.FontStyle;
initBackBrush = (SolidColorBrush)wfh.Background;
initForeBrush = (SolidColorBrush)wfh.Foreground;
(wfh.Child as MyControl1).OnButtonClick += new MyControl1.MyControlEventHandler(Pane1_OnButtonClick);
UIIsReady = true;
}
前述の XAML コードによって、MyControl1 が WindowsFormsHost 要素の子要素コレクションに追加されているため、WindowsFormsHost 要素の Child をキャストして MyControl1 への参照を取得できます。その後、その参照を使用して、イベント ハンドラを OnButtonClick にアタッチすることができます。
コントロール自体への参照を提供するだけでなく、WindowsFormsHost ではさまざまなコントロールのプロパティも公開されており、ページからそれを操作できます。初期化コードは、後でアプリケーションで使用するため、これらの値をプライベート グローバル変数に代入します。
OnButtonClick イベントの処理
ユーザーがコントロールのボタンのいずれかをクリックすると、MyControl1 が OnButtonClick イベントを発生させます。Page1 クラスに次のコードを追加します。
'Handle button clicks on the Windows Form control
Private Sub Pane1_OnButtonClick(ByVal sender As Object, ByVal args As MyControlEventArgs)
txtName.Inlines.Clear()
txtAddress.Inlines.Clear()
txtCity.Inlines.Clear()
txtState.Inlines.Clear()
txtZip.Inlines.Clear()
If args.IsOK Then
txtName.Inlines.Add(" " + args.MyName)
txtAddress.Inlines.Add(" " + args.MyStreetAddress)
txtCity.Inlines.Add(" " + args.MyCity)
txtState.Inlines.Add(" " + args.MyState)
txtZip.Inlines.Add(" " + args.MyZip)
End If
End Sub
End Class
//Handle button clicks on the Windows Form control
private void Pane1_OnButtonClick(object sender, MyControlEventArgs args)
{
txtName.Inlines.Clear();
txtAddress.Inlines.Clear();
txtCity.Inlines.Clear();
txtState.Inlines.Clear();
txtZip.Inlines.Clear();
if (args.IsOK)
{
txtName.Inlines.Add( " " + args.MyName );
txtAddress.Inlines.Add( " " + args.MyStreetAddress );
txtCity.Inlines.Add( " " + args.MyCity );
txtState.Inlines.Add( " " + args.MyState );
txtZip.Inlines.Add( " " + args.MyZip );
}
}
テキスト ボックスのデータは、MyControlEventArgs オブジェクトに格納されます。ユーザーが [OK] ボタンをクリックすると、イベント ハンドラはデータを抽出して、MyControl1 の下のパネルに表示します。
コントロールのプロパティの変更
WindowsFormsHost 要素は、ホストされるコントロールのいくつかの既定のプロパティを公開します。これにより、ページのスタイルにより一致するように、コントロールの外観を変更できます。左側のパネルにある一連のオプション ボタンを使用すると、色やフォントのプロパティを変更できます。各ボタン セットには Click イベントに対するハンドラがあり、ユーザーによるオプション ボタンの選択を検出して、コントロールの対応するプロパティを変更します。次のコードを Page1 クラスにコピーします。これで、アプリケーションをコンパイルして実行できます。
Private Sub BackColorChanged(ByVal sender As Object, ByVal e As RoutedEventArgs)
If sender.Equals(rdbtnBackGreen) Then
wfh.Background = New SolidColorBrush(Colors.LightGreen)
ElseIf sender.Equals(rdbtnBackSalmon) Then
wfh.Background = New SolidColorBrush(Colors.LightSalmon)
ElseIf UIIsReady = True Then
wfh.Background = initBackBrush
End If
End Sub
Private Sub ForeColorChanged(ByVal sender As Object, ByVal e As RoutedEventArgs)
If sender.Equals(rdbtnForeRed) Then
wfh.Foreground = New SolidColorBrush(Colors.Red)
ElseIf sender.Equals(rdbtnForeYellow) Then
wfh.Foreground = New SolidColorBrush(Colors.Yellow)
ElseIf UIIsReady = True Then
wfh.Foreground = initForeBrush
End If
End Sub
Private Sub FontChanged(ByVal sender As Object, ByVal e As RoutedEventArgs)
If sender.Equals(rdbtnTimes) Then
wfh.FontFamily = New FontFamily("Times New Roman")
ElseIf sender.Equals(rdbtnWingdings) Then
wfh.FontFamily = New FontFamily("Wingdings")
ElseIf UIIsReady = True Then
wfh.FontFamily = initFontFamily
End If
End Sub
Private Sub FontSizeChanged(ByVal sender As Object, ByVal e As RoutedEventArgs)
If sender.Equals(rdbtnTen) Then
wfh.FontSize = 10
ElseIf sender.Equals(rdbtnTwelve) Then
wfh.FontSize = 12
ElseIf UIIsReady = True Then
wfh.FontSize = initFontSize
End If
End Sub
Private Sub StyleChanged(ByVal sender As Object, ByVal e As RoutedEventArgs)
If sender.Equals(rdbtnItalic) Then
wfh.FontStyle = FontStyles.Italic
ElseIf UIIsReady = True Then
wfh.FontStyle = initFontStyle
End If
End Sub
Private Sub WeightChanged(ByVal sender As Object, ByVal e As RoutedEventArgs)
If sender.Equals(rdbtnBold) Then
wfh.FontWeight = FontWeights.Bold
ElseIf UIIsReady = True Then
wfh.FontWeight = initFontWeight
End If
End Sub
private void BackColorChanged(object sender, RoutedEventArgs e)
{
if (sender == rdbtnBackGreen)
wfh.Background = new SolidColorBrush(Colors.LightGreen);
else if (sender == rdbtnBackSalmon)
wfh.Background = new SolidColorBrush(Colors.LightSalmon);
else if (UIIsReady == true)
wfh.Background = initBackBrush;
}
private void ForeColorChanged(object sender, RoutedEventArgs e)
{
if (sender == rdbtnForeRed)
wfh.Foreground = new SolidColorBrush(Colors.Red);
else if (sender == rdbtnForeYellow)
wfh.Foreground = new SolidColorBrush(Colors.Yellow);
else if (UIIsReady == true)
wfh.Foreground = initForeBrush;
}
private void FontChanged(object sender, RoutedEventArgs e)
{
if (sender == rdbtnTimes)
wfh.FontFamily = new FontFamily("Times New Roman");
else if (sender == rdbtnWingdings)
wfh.FontFamily = new FontFamily("Wingdings");
else if (UIIsReady == true)
wfh.FontFamily = initFontFamily;
}
private void FontSizeChanged(object sender, RoutedEventArgs e)
{
if (sender == rdbtnTen)
wfh.FontSize = 10;
else if (sender == rdbtnTwelve)
wfh.FontSize = 12;
else if (UIIsReady == true)
wfh.FontSize = initFontSize;
}
private void StyleChanged(object sender, RoutedEventArgs e)
{
if (sender == rdbtnItalic)
wfh.FontStyle = FontStyles.Italic;
else if (UIIsReady == true)
wfh.FontStyle = initFontStyle;
}
private void WeightChanged(object sender, RoutedEventArgs e)
{
if (sender == rdbtnBold)
wfh.FontWeight = FontWeights.Bold;
else if (UIIsReady == true)
wfh.FontWeight = initFontWeight;
}
参照
処理手順
チュートリアル : Windows Presentation Foundation での Windows フォーム コントロールのホスト
概念
チュートリアル : Windows フォームでの Windows Presentation Foundation コントロールのホスト