簡體   English   中英

WPF中的共享樣式

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM