前言
我们日常开发的时候,经常会遇到需要自定义标题栏的UI设计,采用特定颜色的标题栏或者特定样式的按钮,这个时候就需要自定义标题栏了,wpf中自定义标题栏还是相对容易的。.
一、步骤
1.设置窗口属性
我们要把窗口本身的标题栏去除,因为标题栏不属于我们能控制的部分,我们能控制的只有窗口的客户区域。
ResizeMode="NoResize"WindowStyle="None"
如果需要异型窗口,比如圆角边框或者工具条,则需要加上下面2个属性设置。
AllowsTransparency="True"Background="Transparent"
2.客户区定义标题栏
我们可以在客户区的顶部添加一个容器作为标题栏。
<StackPanel><!--标题栏--><Grid Background="Gray" Height="50" ></Grid><!--客户区--></StackPanel>
二、示例
界面代码
<Window x:Class="WpfApp1.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:sys="clr-namespace:System;assembly=mscorlib"xmlns:local="clr-namespace:WpfApp1"mc:Ignorable="d"Title="MainWindow" Height="370" Width="650"AllowsTransparency="True"Background="Transparent"ResizeMode="NoResize"WindowStyle="None"><StackPanel Margin="10" Background="White"><StackPanel.Effect><DropShadowEffect ShadowDepth="0" BlurRadius="10" Opacity="0.8"/></StackPanel.Effect><!--标题栏--><Grid Background="Gray" Height="50" ><StackPanel Margin="0,0,10,0" HorizontalAlignment="Right" Orientation="Horizontal"><Button Width="40" Height=" 40" VerticalAlignment="Center" Cursor="Hand"><Button.Template><ControlTemplate><Grid Background="Transparent"><Rectangle Width="30" Height="3" Fill="White" ></Rectangle></Grid></ControlTemplate></Button.Template></Button><Button Width="40" Height=" 40" VerticalAlignment="Center" Cursor="Hand"><Button.Template><ControlTemplate><Grid Background="Transparent"><Rectangle Width="30" Height="30" Stroke="White" StrokeThickness="3"></Rectangle></Grid></ControlTemplate></Button.Template></Button><Button Width="40" Height=" 40" VerticalAlignment="Center" Cursor="Hand"><Button.Template><ControlTemplate><Grid Background="Transparent"><Line Width="30" Height="30" X1="0" Y1="0" X2="30" Y2="30" StrokeThickness="3" Stroke="White" ></Line><Line Width="30" Height="30" X1="30" Y1="0" X2="0" Y2="30" StrokeThickness="3" Stroke="White" ></Line></Grid></ControlTemplate></Button.Template></Button></StackPanel></Grid><!--客户区--></StackPanel></Window>
效果预览
