I'm a WPF beginner and I'm kind of stuck at figuring out why below XAML doesn't do what I believe it should:
<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>
This should cause the <Separator />
to have the margins of 4,6
but it only does so if I explicitly specify x:Key
on the style and the <Separator Style="..." />
.
From what I learned so far, my <Style TargetType="{x:Type Separator}">
should apply to all separators inside the <ToolBar>
, its child elements, its children's children and so on.
What I'm doing wrong?
You should set the x:Key
to {x:Static ToolBar.SeparatorStyleKey}
for the style be applied within 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>
This is because the ToolBar
class contains some "special" logic for applying default styles to some type of controls including the Separator
: https://referencesource.microsoft.com/#PresentationFramework/src/Framework/System/Windows/Controls/ToolBar.cs,5d1684510f45eeb3