不适用于儿童的本地元素范围样式

时间:2017-03-22 13:10:26

标签: wpf xaml wpf-4.5

我是WPF的初学者,我有点想弄清楚为什么XAML不能做我认为应该做的事情:

<ToolBar HorizontalAlignment="Left" Margin="255,250,0,0" VerticalAlignment="Top">
    <ToolBar.Resources>
        <Style TargetType="{x:Type Separator}">
            <Setter Property="Margin" Value="4,6" />
        </Style>
    </ToolBar.Resources>
    <Button Content="Save"/>
    <Button Content="Cancel"/>
    <Separator />
    <Button Content="Options"/>
</ToolBar>

这会导致<Separator />的边距为4,6,但只有在样式和x:Key上明确指定<Separator Style="..." />时才会这样做。

根据我到目前为止所学到的,我的<Style TargetType="{x:Type Separator}">应该适用于<ToolBar>内的所有分隔符,其子元素,子女的子等等。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您应该将x:Key设置为{x:Static ToolBar.SeparatorStyleKey},以便在ToolBar中应用该样式:

<ToolBar HorizontalAlignment="Left" Margin="255,250,0,0" VerticalAlignment="Top">
    <ToolBar.Resources>
        <Style x:Key="{x:Static ToolBar.SeparatorStyleKey}" TargetType="{x:Type Separator}">
            <Setter Property="Margin" Value="4,6" />
            <Setter Property="Background" Value="Red" />
        </Style>
    </ToolBar.Resources>
    <Button Content="Save"/>
    <Button Content="Cancel"/>
    <Separator />
    <Button Content="Options"/>
</ToolBar>

这是因为ToolBar类包含一些“特殊”逻辑,用于将默认样式应用于某些类型的控件,包括Separatorhttps://referencesource.microsoft.com/#PresentationFramework/src/Framework/System/Windows/Controls/ToolBar.cs,5d1684510f45eeb3

相关问题