2011-02-10 20 views
0

我定义了一个自定义的WPF样式。我想要网格中的任何按钮都是红色的。但如果我定义这种风格,整个网格是红色!为什么?我明确定义了Button.Background。为什么WPF样式应用于父控件?

<Window x:Class="WpfApplication2.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 

    <Window.Resources> 
     <Style x:Key="MyStyle"> 
      <Setter Property="Button.Background" Value="Red" /> <!-- Only inner buttons --> 
     </Style>    
    </Window.Resources> 

    <Grid Style="{StaticResource MyStyle}"> 
     <Button Content="Go" Margin="29,36,385,239" /> 
    </Grid> 
</Window> 

回答

0

您不能将TargetType设置为按钮,以便此样式仅应用于按钮?

<Style x:Key="MyStyle" TargetType="Button"> 
    <Setter Property="Background" Value="Red" /> 
</Style> 
+0

不,因为样式必须应用于网格。并应包含不同内部控件的所有不同样式 – Robert 2011-02-10 13:16:07

1

要实现你以后,我认为你得给内Style.Resources限定内部Style秒。这将使所有Button S IN的Grid拿起“内部” Style,除非它们显式地使用其他Style

<Window.Resources> 
    <Style x:Key="MyStyle"> 
     <Style.Resources> 
      <!-- Only inner buttons --> 
      <Style TargetType="Button"> 
       <Setter Property="Background" Value="Red" /> 
      </Style> 
     </Style.Resources> 
    </Style> 
</Window.Resources> 
<Grid Style="{StaticResource MyStyle}"> 
    <Button Content="Go" Margin="29,36,385,239" /> 
</Grid> 

由于Button.Background不是附加属性(例如不同TextBlock.Foreground),该Background韩元不适用于Grid中的Button

但至于“为什么Grid拿起Background”我无法告诉你。这对我来说似乎是一个错误。 背景ButtonControl背景继承了Grid所以就我所看到的,该值不应由Grid使用,但我可能失去了一些东西

也从Panel继承如果您尝试直接设置Button.BackgroundGrid

错误MC3015你会得到以下错误:附加属性 “Button.Background”未在 “网格”中定义或它的基类之一。

0

不幸的是,风格不像那样工作。如果你有一个已知的孩子集合,你可以用类似的信息(丑陋的)作弊:

<Setter Property="{Binding RelativeSource={RelativeSource Self} Path=Children[0].Background}" Value="Red" /> 

当然,如果你知道孩子们指数这只是工作,而且是相当脆弱的。我不确定它是否适用于你的情况b/c你说你必须将样式应用于网格,所以我猜测网格内容正在动态生成。

相关问题