[10 行でズバリ!! コントロールのテンプレート化と再利用 (C#)]をダウンロードする。
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="300" Width="300">
<Window.Resources>
<!-- すべてのテキストボックスに適用されるスタイル -->
<Style TargetType="TextBox">
<!-- Templateプロパティの設定 -->
<Setter Property="Template">
<Setter.Value>
<!-- テンプレートの定義 -->
<ControlTemplate>
<Border CornerRadius="5" BorderThickness="5" BorderBrush="Red">
<ScrollViewer x:Name="PART_ContentHost"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<StackPanel>
<TextBox Width="200" Height="30" Margin="10" x:Name="textbox1" />
<Button Width="100" Height="30" Click="button1_Click">Button</Button>
</StackPanel>
</Window>
<Window>階層1
<Window.Resources>階層2-1
<Style >階層3-1:"TextBox"
<Setter>階層4-1:"Template"
<Setter.Value>階層5-1
<ControlTemplate>階層6-1
<Border>階層7-1:"Red"
<ScrollViewer />階層8-1:"PART_ContentHost"
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<StackPanel>階層2-2
<TextBox/>階層3-2
<Button></Button>階層3-2
</StackPanel>
</Window>
(1)XAMLを理解するには、まずXAMLの階層構造を理解する必要があります。(サンプルは上記のようになります。)
using System.Windows;
namespace MyTextbox
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
MessageBox.Show(this.textbox1.Text);
}
}
}