2013-08-02 43 views
2

我试图在XAML中为WPF Window设置Style。我可以在VS Designer中看到我的更改,但是当我运行该应用程序时,它始终会获得默认的Style为什么WPF窗口总是得到默认样式?

不工作:

<Style TargetType="Window"> 
    <Setter Property="Background" Value="Red"/> 
</Style> 

如果我给那个Style密钥和应用该StyleWindow然后它工作。

工作:

<Style x:Key="window" TargetType="Window"> 
    <Setter Property="Background" Value="Red"/> 
</Style> 

有任何理由需要给StyleWindow关键?

任何人都可以请解释发生了什么?

回答

0

尝试

<Style TargetType="{x:Type Window}"> 
    <Setter Property="Background" Value="Red"/> 
</Style> 
+2

,它是如何从不同什么OP张贴在他的问题? – Nitesh

1

有必要增加建设Window

Style="{StaticResource {x:Type Window}}" 

风格是文件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> 

窗口在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> 
0

样式中的目标类型不适用于派生类型。

无论您使用StaticResource对所有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

定义在资源style for your type (derived window)这样的 -

<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> 
+0

感谢您的answer.but我已经搜索了谷歌无法找到任何与以下相关的链接。“样式中的目标类型不适用于派生类型。”你可以请分享任何链接? – Ravuthasamy

+0

请参阅链接 - http://stackoverflow.com/questions/4279773/wpf-window-style-not-being-applied和http://stackoverflow.com/questions/431940/how-to-set-default- WPF的窗口风格应用程序内,XAML –