Silverlight で Style をまとめて適用する

Silverlight には x:Type マークアップ拡張が無いので、たくさんのコントロールに同じ Style を適用したい場合、一つ一つ指定しなければいけません。これが非常に面倒な作業です。

しかし、Silverlight Toolkit に含まれている ImplicitStyleManager を使えば、この面倒な作業から解放されます。百聞は一見にしかず。サンプルコードをどうぞ。

<UserControl x:Class="StyleSample.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:theming="clr-namespace:Microsoft.Windows.Controls.Theming;assembly=Microsoft.Windows.Controls.Theming"
    Width="400" Height="300">
    <!--ImplicitStyleManager の ApplyMode 添付プロパティを使用する-->
    <StackPanel x:Name="LayoutRoot" Background="White" theming:ImplicitStyleManager.ApplyMode="Auto">
        <StackPanel.Resources>
            <!--このスタイルを StackPanel 上のすべての Button に適用する-->
            <Style TargetType="Button">
                <Setter Property="Foreground" Value="Red"/>
            </Style>
        </StackPanel.Resources>
        <Button Content="ボタン1"/>
        <Button Content="ボタン2"/>
        <Button Content="ボタン3"/>
    </StackPanel>
</UserControl>

ImplicitStyleManager は Microsoft.Windows.Controls.Theming.dll 内に定義されています。このサンプルの実行画面がこちら。

f:id:griefworker:20090305120043p:image

StackPanel 上に置かれているすべての Button に Style が適用されています。これは便利だ…。