Markup Extensions

以前の投稿で書きましたが、XAMLでは各エレメントのプロパティがString型以外の場合には、TypeConverterによって文字列から必要な型の値やクラスのインスタンスが生成されて設定されるようになっています。
ところが、このTypeConverterを使う方法では対応できない場合あがあります。それは、すでに定義されているオブジェクトをプロパティの値として設定したい場合です。例としては、すでに配置されているほかのエレメントやそのプロパティ、定義されたリソースなどがあるかと思います。
このために用意されている機能として、XAMLにはMarkup Extensionsというものがあります。

http://windowssdk.msdn.microsoft.com/en-us/library/ms747254.aspx

いくつか用意されているMarkup Extensionsで一番よく見かけるのがBindingStaticResourceです。
Bindingについては、川西さんのblogで紹介されていますのでこちらを見るとどのようなものかわかるかと思います。

Windows Presentation Foundation "Property Binding" – 川西 裕幸のブログ

ここでは、StaticResourceを使う場合を紹介したいと思います。


XAML

<Window x:Class="Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="StaticResourceSample" Height="300" Width="300"
    >
 
  <Window.Resources>
    <RotateTransform x:Key="Naname" Angle="45" CenterX="25" CenterY="25"/>
    <SolidColorBrush x:Key="MyBrush" Color="Gold"/>
  </Window.Resources>
 
  <StackPanel Orientation="Horizontal" Height="70">
    <Button Margin="10" Content="Button1" RenderTransform="{StaticResource Naname}"/>
    <Button Margin="10" Content="Button1"/>
    <Button Margin="10" Content="Button1" RenderTransform="{StaticResource Naname}" Background="{StaticResource MyBrush}"/>
    <Button Margin="10" Content="Button1" Background="{StaticResource MyBrush}"/> 
  </StackPanel>
 
</Window>





最初の部分ではTransformとBrushをリソースとしてあらかじめ定義しています。ボタンのRenderTransformプロパティとBackgroundプロパティに、Markup ExtensionsのStaticResourceを使って定義されたオブジェクトを設定しています。Markup Extensionsは中かっこ(カーリーブラケット)でくくります。