2014-10-08 59 views
1

我相信这可以很容易地完成,但我是一个天真的新手,对我来说是如此光秃秃的。WPF中的共享样式

如果我想让UserControl中的所有TextBlock元素或UserControl的一部分具有FontWeight="Bold"TextAlignment="Right"?有一些我可以为某个范围内的TextBlock元素设置一些风格,所以我不必重复所有这些属性?

回答

0

如果你把它放在你的资源中,所有的文本块都会变成相同的。

<Style TargetType="{x:Type TextBlock}"> 
    <Setter Property="FontWeight" Value="Bold"/> 
    <Setter Property="TextAlignment" Value="Right"/> 
</Style> 

另外,您也可以从TextBlock(比如说,BoldTextBlock)子类,并用它作为目标类型。这样,您可以在同一控制使用普通的TextBlocks特殊的TextBlocks

<Style TargetType="{x:Type BoldTextBlock}"> 
    <Setter Property="FontWeight" Value="Bold"/> 
    <Setter Property="TextAlignment" Value="Right"/> 
</Style> 
+0

加分,我怎么能做到这一点的像'Grid.Column'。它似乎并没有按照你向我展示的方式工作。 – ProfK 2014-10-08 17:18:04

+0

不确定你的意思是什么'Grid.Column'。你的意思是说使用特定的风格......只有一列?这有帮助吗? http://stackoverflow.com/a/853082/1732567 – Vlad 2014-10-08 17:25:39

+0

我想在网格列0中的所有我的'TextBlock'元素。他们是标签 - 他们的输入元素都在网格列1.我想避免重复所有标记也是如此。 – ProfK 2014-10-08 17:58:11

1

是,创建一个样式,没有x:Key,这将是范围

内应用到指定TargetType的所有项目例如,为了使所有的TextBlock有FontWeight="Bold"TextAlignment="Right"只有特定UserControl内,你可以使用这样的事情:

<UserControl.Resources> 
    <Style TargetType="{x:Type TextBlock}"> 
     <Setter Property="FontWeight" Value="Bold" /> 
     <Setter Property="TextAlignment" Value="Right" /> 
    </Style> 
</UserControl.Resources> 
+0

谢谢。艰难的决定,但你的答案是一样的,@Vlad几秒钟打败你。 – ProfK 2014-10-08 17:15:04