最近一直很苦恼关于WPF窗口样式的问题,研究了好多Demo中的自定义样式,接下来整理下目前比较用的上的几种:
本篇写的是一个比较有限制的自定义窗口样式,若是只想实现icon和标题文本居中则可以使用,不过注意:这个自定义样式与WindowsFormsHost控件是有冲突的。并且放大缩小关闭按钮会被盖住或模糊(应为在上面添加了至关于一层蒙版的感受)。
下面是自定义样式,可写在资源字典Dictionary1.xaml中:代码中窗口标题行背景颜色的透明必定不能设置不透明,不然会将放大缩小关闭按钮遮盖住。若是对背景颜色没要求,建议不要设置背景颜色,或者把代码中标红部分变为0便可。app
<!--通用窗口模板-icon和标题文本居中-保留窗口功能事件--> <ControlTemplate x:Key="FlatWindowTemplate" TargetType="{x:Type Window}"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="30"/> <RowDefinition Height="1*"/> </Grid.RowDefinitions> <!-- Opacity of < 1.0 helps show the minimize, maximize and close buttons --> <Border Grid.Row="0" > <Border.Background> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0" Opacity="0.6"> <GradientStop Color="#FFFBFBFC" Offset="1"/> <GradientStop Color="#FFF3F7FB" Offset="0.021"/> </LinearGradientBrush> </Border.Background> <Grid VerticalAlignment="Center"> <Grid.ColumnDefinitions> <ColumnDefinition Width="5*" /> <ColumnDefinition Width="6*"/> </Grid.ColumnDefinitions> <StackPanel Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Center" > <!-- System Menu --> <Button Width="22" HorizontalAlignment="Center" Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" WindowChrome.IsHitTestVisibleInChrome="True" Command="{x:Static SystemCommands.ShowSystemMenuCommand}" CommandParameter="{Binding ElementName=_MainWindow}"> <!-- Make sure there is a resource with name Icon in MainWindow --> <Image Source="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Icon}" WindowChrome.IsHitTestVisibleInChrome="True"/> </Button> <!-- Window Title - Center Aligned --> <TextBlock FontSize="13" TextAlignment="Center" VerticalAlignment="Center" Text="{Binding Title, RelativeSource={RelativeSource TemplatedParent}}" /> </StackPanel> </Grid> </Border> <!-- This is the Window's main content area --> <!-- Top margin 44 = WindowChrome ResizeBorderThickness (4) + CaptionHeight(40) --> <!-- Bottom margin 1 is somewhat arbitrary --> <AdornerDecorator Grid.Row="1" > <Border Background="White" Opacity="1"> <ContentPresenter Content="{Binding Content, RelativeSource={RelativeSource TemplatedParent}}"/> </Border> </AdornerDecorator> </Grid> </ControlTemplate> <!-- 通用窗口样式-icon和标题文本居中-保留窗口功能事件 --> <Style x:Key="FlatWindowStyle" TargetType="Window"> <Setter Property="Template" Value="{StaticResource FlatWindowTemplate}"></Setter> <Setter Property="WindowChrome.WindowChrome"> <Setter.Value> <WindowChrome GlassFrameThickness="-1" ResizeBorderThickness="4" CaptionHeight="30"/> </Setter.Value> </Setter> </Style>
而后在window窗体中引用它:
code
Style="{DynamicResource FlatWindowStyle}" //window中添加,引用通用窗口样式 <Window.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="pack://application:,,,/路径/Dictionary1.xaml" />//引用资源文件 </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Window.Resources>
上面这种样式局限性较多,实现的效果也较少。orm