WPF default themes and custom styles not working together
Hey, I have a WPF application targeted at XP machines. The problem is that we wish to run with a WPF XP luna theme rather than classic and most of our clients run in classic mode. Our clients are all internal, it's just that their machines were configured with XP classic.
In theory, this is as simple as adding this to the application:
<ResourceDictionary Source="/PresentationFramework.Luna, Version=3.0.0.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35,
ProcessorArchitecture=MSIL;component/themes/luna.normalcolor.xaml" />
In practice, as soon as a touch any of the styles (say add a margin to TextBox), they styles seem to revert back to classic theme.
This displays correctly (Style Luna):
<TextBox Width="80" Height="20" />
This displays correctly (Style Luna):
<TextBox Width="80" Height="20" Background="Brown">
This displays incorrectly (Style Classic), note it does not matter now many nodes there are in the style block - zero is enough to confuse things:
<TextBox.Style><Style></Style></TextBox.Style></TextBox>
Long and short, overriding the default OS theme seems to preclude further use of styles. What am I missing here?
See the select answer for 80% of the story. The full story is this: I must supply the ‘BasedOn’ setting as well. Unfortunately, this means we can not override, say textbox, without causing a loop. Defining:
<Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">开发者_开发问答
<Setter Property="Margin" Value="0,2,0,2" />
:
</Style>
would result in the error: "a loop was detected in the property expression". The way I chose to get around this was to force named styles everywhere. For example:
<Style x:Key="TextBase" TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
<Setter Property="Margin" Value="0,2,0,2" />
:
</Style>
<Style x:Key="Text25Chars" TargetType="{x:Type TextBox}" BasedOn="{StaticResource TextBase}">
<Setter Property="Margin" Value="0,2,0,2" />
:
</Style>
try this:
<TextBox>
<TextBox.Style>
<Style BasedOn="{StaticResource {x:Type TextBox}}">
</Style>
</TextBox.Style>
</TextBox>
edit: forgot the TargetType, this works for me:
<Window x:Class="Test.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>
<ResourceDictionary Source="/PresentationFramework.Luna, Version=3.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35,
ProcessorArchitecture=MSIL;component/themes/luna.normalcolor.xaml" />
</Window.Resources>
<TextBox>
<TextBox.Style>
<Style TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}">
<Setter Property="Foreground" Value="Blue" />
</Style>
</TextBox.Style>
tototototottototo
</TextBox>
</Window>
精彩评论