通過把同樣的內嵌樣式提升到資源中(正如第一章介紹的),我們可以給它 一個名字,以及按名字使用它在我們的Button執行個體上,正如樣本5-5。
樣本5-5
<!-- Window1.xaml -->
<Window >
<Window.Resources>
<Style x:Key="CellTextStyle">
<Setter Property="Control.FontSize" Value="32" />
<Setter Property="Control.FontWeight" Value="Bold" />
</Style>
</Window.Resources>
<Button Style="{StaticResource CellTextStyle}" x:Name="cell00" />
</Window>
在樣本5-5中,我們在屬性中使用到Control首碼取代Button首碼,從而允許 樣式更廣泛的應用,正如我們將要看到的。
5.3.1 TargetType屬性
方便起見,如果所有的屬性可以在一個共用類中設定,像我們樣本中的 Control,我們可以提升這個類的首碼,放入TargetType屬性中,並將其從屬性 的名稱中移除掉。如樣本5-6所示。
樣本5-6
<Style x:Key="CellTextStyle" TargetType="{x:Type Control}">
<Setter Property="FontSize" Value="32" />
<Setter Property="FontWeight" Value="Bold" />
</Style>
當提供了一個TargetType屬性,你能夠只設定該類型可接受的屬性。如果你 想要在繼承樹下擴充一組大量的屬性,你可以通過使用一個衍生類別型來做到這些 ,如樣本5-7。
樣本5-7
<Style x:Key="CellTextStyle" TargetType="{x:Type Button}">
<!-- IsCancel is a Button-specific property -->
<Setter Property="IsCancel" Value="False" />
<Setter Property="FontSize" Value="32" />
<Setter Property="FontWeight" Value="Bold" />
</Style>