WPFにあってSilverlight 2にないシリーズ「リソースディクショナリファイルの利用」

WPFでは、Visual Studioのアイテムテンプレートに「リソース ディクショナリ (WPF)」という項目が存在します。



追加したリソースディクショナリを下記のように記述し、


Dictionary1.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style x:Key="bstyle" TargetType="Button">
        <Setter Property="Foreground" Value="Blue"/>
    </Style>
</ResourceDictionary>


Dictionary1.xamlで定義されたリソースをWindow1.xamlの中のGrid要素のリソースとして追加する記述を下記のように記述すると、


Window1.xaml
<Window x:Class="Window1"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   Title="Window1" Height="300" Width="300" FontSize="64">
    <Grid>
        <Grid.Resources>
            <ResourceDictionary Source="Dictionary1.xaml"/>
        </Grid.Resources>
        <Button Style="{StaticResource bstyle}" Content="Button"/>
    </Grid>
</Window>


下記のようにDictionary1.xamlで定義したスタイルが反映されます。





Silverlight 2の場合ResourceDictionaryクラスは存在しますが、Sourceプロパティがないため上記のようにリソースディクショナリを利用することはできません。現時点では、コードからリソースディクショナリを読み込んで利用するか、カスタムコントロールの外観定義(genelic.xaml)専用ということになるかと思います。