Поделиться через


Tips & Tricks: How to undo an implicit style

You can define a style that gets used by all elements of a type, such as this case (this causes all buttons in the page to have a blue background):

<Page xmlns=https://schemas.microsoft.com/winfx/2006/xaml/presentation

xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml">

<Page.Resources>

<Style TargetType="{x:Type Button}">

<Setter Property="Background" Value="Blue"/>

</Style>

</Page.Resources>

<StackPanel>

<Button>Click</Button>

<Button>Clack</Button>

</StackPanel>

</Page>

But what if you want one of the buttons to break from this standard, and go back to “normal”? You can do that by overriding the Style on that button, and specifically setting it to null:

<Page xmlns=https://schemas.microsoft.com/winfx/2006/xaml/presentation

xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml">

<Page.Resources>

<Style TargetType="{x:Type Button}">

<Setter Property="Background" Value="Blue"/>

</Style>

</Page.Resources>

<StackPanel>

<Button >Click</Button>

<Button Style="{x:Null}">Clack</Button>

</StackPanel>

</Page>

Why does that work? A control, such as a button, actually has two styles – the local style (the Style property) and the theme (or “default”) style. The theme style is defined by the control or in the system. But when you set a Style on a control, either explicitly or through in the Resources property, you’re overriding the theme style for the properties you define in that style.

So in the above example, the button style becomes the element Style for all buttons unless overridden. By setting the second button’s style to null, it no longer picks up that style, and only uses the theme style. But in neither case is e.g. the Foreground property effected, because the Style defined in the Page.Resources doesn’t set that property. So both buttons use the Foreground property value from the theme style.

 

OverrideImplicitStyle.jpg

Comments

  • Anonymous
    March 06, 2009
    Thank you for the article. It is very helpful and has lots of good tips!