开发者

Why a WPF Style is applied to a parent control?

I defined a custom WPF Style. I want any button in the Grid is Red. But if I define this style, the whole grid is red!! Why? I explicitly defined Button.Background.

<Window x:Class="WpfApplicati开发者_StackOverflow中文版on2.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>


To achieve what you're after I think you're gonna have to define the inner Styles within Style.Resources. This will make all the Buttons in the Grid pick up the "inner" Style unless they explictly use another 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>

Since Button.Background isn't an attached property (unlike e.g. TextBlock.Foreground), the Background won't be applied to the Buttons in the Grid.

But as for the "Why does the Grid pick up the Background" I couldn't tell you. It seems like a bug to me. Background for a Button is inherited from Control and Background for a Grid is inherited from Panel so as far as I can see, that value shouldn't be used by the Grid but I might be missing something

Also, you'll get the following error if you try to set Button.Background directly on a Grid

error MC3015: The attached property 'Button.Background' is not defined on 'Grid' or one of its base classes.


Can't you set the TargetType to button so that this style is only applied to a Button?

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


Sadly, styles don't work like that. If you have a known child collection, you can cheat with something like (ugly):

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

Of course, this only works if you know the children indices, and it's pretty fragile. I'm not sure that it'll work for your case b/c you said that you must apply the style to the grid, so I'm guessing the grid contents are getting dynamically generated.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜