2017-07-27 37 views
2

是否有方法可以定義可添加到項目的屬性組合?元素屬性繼承和重用XAML更佳實踐

所以不是:

<TextBlock Text="Hi" Foreground="Gray" Margin="0,8,0,0" FontFamily="Segoe UI"/> 
<TextBlock Text="there" Foreground="Gray" Margin="0,8,0,0" FontFamily="Segoe UI"/> 

我會做類似

<PropertyCombo name="textBlockCombo1" 
    Foreground="Gray" Margin="0,8,0,0" FontFamily="Segoe UI" 
. 
. 
. 
<TextBlock Text="Hi" ImportProperty="textBlockCombo1"/> 
<TextBlock Text="there" ImportProperty="textBlockCombo1"/> 

回答

1

雅,從而真正使得維護和可讀性容易得多....

就做這樣的事情這要麼在父級實例級別,要麼更高級的繼承樹,就像DOM一樣。

<StackPanel> 
    <StackPanel.Resources> 
     <Style TargetType="TextBlock"> 
     <Setter Property="FontSize" Value="30"/> 
     <Setter Property="FontWeight" Value="Bold"/> 
     <Setter Property="Foreground" Value="Green"/> 
     <Setter Property="Margin" Value="5,10"/> 
     <Setter Property="Text" Value="Blah"/> 
     </Style> 
    </StackPanel.Resources/> 

    <TextBlock/> 
    <TextBlock/> 
    <TextBlock/> 
    <TextBlock/> 
    <TextBlock/> 

</StackPanel> 

您還可以製作x:Key靜態樣式並將它們放在資源字典中,並在需要時調用它們,如在實例中;

<Style TargetType="TextBlock" x:Key="AwesomeStyleName"> 
    <Setter Property="FontSize" Value="30"/> 
    <Setter Property="FontWeight" Value="Bold"/> 
    <Setter Property="Foreground" Value="Green"/> 
    <Setter Property="Margin" Value="5,10"/> 
    <Setter Property="Text" Value="Blah"/> 
</Style> 

然後調用實例;

<TextBlock Style="{StaticResource AwesomeStyleName}"/> 

或者將其應用於一個組中,例如:

<StackPanel> 
    <StackPanel.Resources> 
     <Style TargetType="TextBlock" BasedOn="{StaticResource AwesomeStyleName}"/> 
    </StackPanel.Resources/> 

    <TextBlock/> 
    <TextBlock/> 
    <TextBlock/> 

</StackPanel> 

希望這會有所幫助,歡呼聲。

+0

正是我所需要的,謝謝一堆! – isebarn

+0

任何時候,都有一個愉快的週末! –