Reputation: 599
I have tried to set the Style
for WPF Window
in XAML. I am able to see my changes in VS Designer, but when I run the application it will always get the default Style
.
Not Working:
<Style TargetType="Window">
<Setter Property="Background" Value="Red"/>
</Style>
If I give that Style
with Key and applying that Style
to Window
then it is working.
Working:
<Style x:Key="window" TargetType="Window">
<Setter Property="Background" Value="Red"/>
</Style>
There is any reason need to give Style
with key for Window
?
Can any one please explain what is going on?
Upvotes: 2
Views: 1120
Reputation: 81243
Target types in style doesn't get applied on derived types.
Either you use StaticResource
to apply key on all your windows -
<Application x:Class="WpfApplication4.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication4"
StartupUri="MainWindow.xaml">
<Application.Resources>
<Style x:Key="MyStyle" TargetType="Window">
<Setter Property="Background" Value="Red"/>
</Style>
</Application.Resources>
</Application>
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Style="{StaticResource MyStyle}">
OR
Define a style for your type (derived window)
in resources like this -
<Application x:Class="WpfApplication4.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
StartupUri="MainWindow.xaml">
<Application.Resources>
<Style TargetType="{x:Type local:MainWindow}">
<Setter Property="Background" Value="Red"/>
</Style>
</Application.Resources>
</Application>
Upvotes: 0
Reputation: 22702
It is necessary to add construction in Window
:
Style="{StaticResource {x:Type Window}}"
Style is in the file App.xaml
:
<Application x:Class="WindowStyleHelp.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
<!-- In this case, the key is optional -->
<Style x:Key="{x:Type Window}" TargetType="{x:Type Window}">
<Setter Property="Background" Value="Pink" />
</Style>
</Application.Resources>
</Application>
Window in XAML:
<Window x:Class="WindowStyleHelp.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"
Style="{StaticResource {x:Type Window}}"
WindowStartupLocation="CenterScreen">
<Grid>
</Grid>
</Window>
Upvotes: 1
Reputation: 1118
Try
<Style TargetType="{x:Type Window}">
<Setter Property="Background" Value="Red"/>
</Style>
Upvotes: 0