1

我是一名 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>,它的子元素,它的子元素等等。

我做错了什么?

4

1 回答 1

1

您应该将样式设置x:Key{x:Static ToolBar.SeparatorStyleKey}在 a 中应用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

于 2017-03-22T13:37:20.673 回答