WPF マークアップファイルにC#の部分コードファイルを関連付ける
前回のマークアップファイルにC#の分離コードファイルを追加します。
追加するC#のクラスはマークアップファイルと同じにする必要があります。
MainWindow.xamlの場合はMainWindow.xaml.csです。
TextBoxコントロールのTextプロパティに ButtonコントロールのClickイベントで "Hello World" を設定します。
分離コードファイルを作成します。
using System;
using System.Windows.Controls;
using System.Windows;
namespace Test {
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
}
public void Button1Clicked(object sender, RoutedEventArgs e) {
_text1.Text = "Hello World";
}
}
}
MainWindow.xamlを作成します。
<Window
x:Class='Test.MainWindow'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
Title='Hello World'>
<WrapPanel>
<Button Click='Button1Clicked'>Hello World1</Button>
<Button>Hello World2</Button>
<TextBox x:Name='_text1'></TextBox>
</WrapPanel>
</Window>
x:Classでクラスを指定します。
Clickイベントで処理するメソッド名を指定します。
最後にTextBoxに x:Name で名前を指定します。
C#ファイルをインクルードするようにプロジェクトファイルを作成します。
<Project
DefaultTargets='Build'
xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<PropertyGroup>
<Configuration>Debug</Configuration>
<Platform>AnyCPU</Platform>
<RootNamespace>Test</RootNamespace>
<AssemblyName>Test</AssemblyName>
<OutputPath>.\bin\Debug\</OutputPath>
</PropertyGroup>
<ItemGroup>
<Reference Include='System' />
<Reference Include='WindowsBase' />
<Reference Include='PresentationCore' />
<Reference Include='PresentationFramework' />
</ItemGroup>
<ItemGroup>
<Compile Include='MainWindow.xaml.cs' />
<Page Include='MainWindow.xaml' />
<ApplicationDefinition Include='app.xaml' />
</ItemGroup>
<Import Project='$(MSBuildBinPath)\Microsoft.CSharp.targets' />
<Import Project='$(MSBuildBinPath)\Microsoft.WinFX.targets' />
</Project>