元素属性继承&重用XAML更好的实践

时间:2017-07-27 09:24:15

标签: 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 个答案:

答案 0 :(得分:1)

Ya,它真正使维护和可读性变得更加容易....

只需在父实例级别执行类似的操作,或者甚至在树的更高位置执行,例如从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>

希望这会有所帮助,欢呼。