BooMark-プログラミングや美術のあれこれ-

半歩ずつでも進めばよろし

【WPF】Resourcesを使って共通の設定をする

コントロールをまとめて設定したいときにApplication.Resources、Window.Resourcesを使うと便利。

▽▼完成図▼▽

f:id:boomark:20220306235243p:plain


▽▼ソースコード▼▽

■App.xaml
prism:PrismApplication x:Class="MyWorkProject.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
	     xmlns:prism="http://prismlibrary.com/"
             xmlns:local="clr-namespace:MyWorkProject">
    <Application.Resources>
        <SolidColorBrush x:Key="Grean" Color="PaleGreen"/>
    </Application.Resources>
</prism:PrismApplication>
■MainWindow.xaml
<Window x:Class="MyWorkProject.Views.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:prism="http://prismlibrary.com/"
        prism:ViewModelLocator.AutoWireViewModel="True"
        Title="{Binding Title}" Height="350" Width="525">
    <Window.Resources>
        <SolidColorBrush x:Key="Grey" Color="DarkGray"/>
        <Style TargetType="Button">
            <Setter Property="HorizontalContentAlignment" Value="Left"/>
            <Setter Property="Background" Value="Beige"/>
            <Setter Property="Foreground" Value="Blue"/>
            <Setter Property="FontWeight" Value="Heavy"/>
        </Style>
    </Window.Resources>
    
    <Grid>
        <StackPanel>
            <Button Content="ボタン(App.Resources&lt;SolidColorBrush&gt;, Win.Resources&lt;Style&gt;)"
                    Background="{StaticResource Grean}"/>
            <Button Content="ボタン(Win.Resources&lt;SolidColorBrush&gt;, &lt;Style&gt;))"
                    Background="{StaticResource Grey}"/>
            <Button Content="ボタン(Win.Resources&lt;Style&gt;)"/>
            <Label Content="ラベル"
                   Background="{StaticResource Grey}"/>
            <TextBlock Text="テキストブロック"
                       Background="{StaticResource Grey}"/>
            <TextBox Text="テキストボックス"
                     Background="{StaticResource Grey}"/>

            <ContentControl prism:RegionManager.RegionName="ContentRegion" />
        </StackPanel>
    </Grid>
</Window>

☆Application.Resources:アプリ全体の共通設定
☆Window.Resources:画面(XAML)内の共通設定
☆上記Resouces内でStyleタグを使うことで、コントロールの種類ごとに設定できる。(上記だと、Buttonの場合に文字の水平位置、背景色、文字色、文字の太さを適用)