[英]Shared styling in WPF
如果我想使UserControl或UserControl部分中的所有TextBlock
元素都具有FontWeight="Bold"
和TextAlignment="Right"
? 是否可以在一定范圍內為TextBlock
元素設置某種樣式,所以不必重復所有這些屬性?
是的,創建一個沒有x:Key
的樣式,它將應用於該范圍內指定TargetType
所有項目
例如,要使所有TextBlock僅在特定的UserControl
具有FontWeight="Bold"
和TextAlignment="Right"
,則可以使用如下代碼:
<UserControl.Resources>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="FontWeight" Value="Bold" />
<Setter Property="TextAlignment" Value="Right" />
</Style>
</UserControl.Resources>
如果將此放在資源中,則所有文本塊都將變為相同。
<Style TargetType="{x:Type TextBlock}">
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="TextAlignment" Value="Right"/>
</Style>
或者,您也可以從TextBlock
BoldTextBlock
子類(例如BoldTextBlock
),並將其用作目標類型。 這樣,您就可以在與特殊文本塊相同的控件中使用常規文本塊
<Style TargetType="{x:Type BoldTextBlock}">
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="TextAlignment" Value="Right"/>
</Style>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.