最近一直很苦惱關於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