在wpf中,您直接定义样式,并设置TargetType="Window",会发现是无效的。要怎么解决呢?
让我们定义一个样式文件,路径为Styles/App.xaml:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Zs.PlayAssists.Styles">
<Style TargetType="Window">
<Setter Property="Height" Value="450"></Setter>
<Setter Property="Width" Value="800"></Setter>
</Style>
</ResourceDictionary>
然后在入口文件App.xaml中添加以下代码:
<Application x:Class="Zs.PlayAssists.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Zs.PlayAssists"
StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Styles/App.xaml"></ResourceDictionary>
<ResourceDictionary Source="/Styles/Control.xaml"></ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
于是我们在入口的主应用程序文件App.xaml文件中引入了样式文件App.xaml文件。请注意,这两个文件虽然名字一样,但文件不同。一个是应用程序入口文件,一个是样式文件。如下图所示:
运行程序,您会发现,您写的高度Height=450,宽度=800对窗体MainWindow是不生效的。
那么要怎么做呢?
方法一,给Window文件添加构造函数:
Style="{StaticResource {x:Type Window}}"
方法二,在资源文件中指定定义:
TargetType="{x:Type local:MainWindow}"
祝您用餐愉快。