ソースコード
App.xaml
<Application x:Class="HelloWorld.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" StartupUri="Page1.xaml"> </Application>
Page1.xaml
<Page x:Class="HelloWorld.Page1" 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="300" d:DesignWidth="300" Title="Page1"> <Grid> <Button Name="button" Width="100" Height="80">Button</Button> </Grid> </Page>
Page1.xaml.cs
using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Shapes; namespace HelloWorld { public partial class Page1 : Page { public Page1() { InitializeComponent(); this.button.Click += (s, e) => { ControlTemplate tempalte = new ControlTemplate(typeof(Button)); FrameworkElementFactory factory = new FrameworkElementFactory(typeof(Rectangle)); tempalte.VisualTree = factory; factory.SetValue(Rectangle.FillProperty, Brushes.Red); factory.SetValue(Rectangle.WidthProperty, 100.0); factory.SetValue(Rectangle.HeightProperty, 80.0); ((Button) button).Template = tempalte; }; } } }