[WPF] 樣式小抄一

  • 1382
  • 0
  • 2016-11-18

小抄主題:

1. 如何設定某個型態(Type)基本的樣式屬性,在套用特定的靜態資源樣式?


1. 如何設定某個型態(Type)基本的樣式屬性,在套用特定的靜態資源樣式?

範例:

        <WrapPanel Orientation="Vertical">
            <WrapPanel.Resources>

                <Style TargetType="Button">
                    <Setter Property="Background" Value="Yellow" />
                    <Setter Property="FontSize" Value="20" />
                </Style>

                <Style x:Key="RedText" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}"  >
                    <Setter Property="FontSize" Value="26" />
                    <Setter Property="Foreground" Value="Red">
                    </Setter>
                </Style>

            </WrapPanel.Resources>
            
            <Button Content="自訂預設樣式" />
            <Button Content="自訂樣式+繼承自訂預設樣式" Style="{StaticResource RedText}" />

        </WrapPanel>

解說:

在 WrapPanel 裡面定義了兩個 Button,其中一個沒有設定 Style 屬性,另一個則有,

其中套用的樣式通常都會定義在 Resources,這樣方便重複使用樣式,

上面的按鈕背景黃色是因為 Resources 裡,定義了這段 Style,

                <Style TargetType="Button">
                    <Setter Property="Background" Value="Yellow" />
                    <Setter Property="FontSize" Value="20" />
                </Style>

而且只指定 TargetType,表示可將這個 WrapPanel 以內的所有 Button 套上背景黃色與字型大小為20,

接著希望下面的按鈕能繼承背景黃色這個特性,同時將前景字的顏色改為紅色,

                <Style x:Key="RedText" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}"  >
                    <Setter Property="FontSize" Value="26" />
                    <Setter Property="Foreground" Value="Red">
                    </Setter>
                </Style>

這裡有段重點,這個樣式需要繼承當前的按鈕樣式,需要使用 BaseOn="{StaticResource {x:Type Button}}",

然後記得要定義一下 x:Key(否則又會套用在這範圍內所有的 Button,實際上同個 Resources 裡面也不允許這麼做),

這樣下面的按鈕就能設定 Style={StaticResource RedText}。

定義 Style 時,記得是由上而下的一個一個去執行的,所以上面的兩個 Style 順序交換的話,結果就會不同。

 不多說,嘗試一下就知道,

        <WrapPanel Orientation="Vertical">
            <WrapPanel.Resources>

                <Style x:Key="RedText" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
                    <Setter Property="FontSize" Value="26" />
                    <Setter Property="Foreground" Value="Red">
                    </Setter>
                </Style>

                <Style TargetType="Button">
                    <Setter Property="Background" Value="Yellow" />
                    <Setter Property="FontSize" Value="20" />
                </Style>

 
            </WrapPanel.Resources>

            <Button Content="自訂預設樣式" />
            <Button Content="自訂樣式+繼承自訂預設樣式" Style="{StaticResource RedText}" />

        </WrapPanel>

你看到上面的按鈕維持一樣,但下面的按鈕卻沒有了黃色背景,

這就是因為我們先定義了 RedText Style,此時 BaseOn Button 的樣式,是不包含我們自定義有黃色背景的樣式,這說明了順序很重要。

 

參考文章:

設定樣式和範本