WPF自定义标题栏

往往原有的标题栏无法满足需求,此时就需要进行自定义标题栏。


重新定义Window的Template

首先,需修改WindowChrome的几个属性

CaptionHeight属性值就是自定义标题栏的高,若值低于自定义窗体模板中的标题部分的高,可能会导致,鼠标点击标题栏无法拖动,因为鼠标此时可能不在CaptionHeight范围之内,所以导致无法拖动。

要使没有玻璃框架的自定义窗口,请将 GlassFrameThickness 属性设置为统一值 0

    <WindowChrome.WindowChrome>
        <WindowChrome CaptionHeight="100" UseAeroCaptionButtons="False" GlassFrameThickness="1" />
    </WindowChrome.WindowChrome>

自定义窗体模板,此时需要用到占位符ContentPresenter来替窗体工作区的内容进行占位,在非工作区中启用交互式元素需 WindowChrome.IsHitTestVisibleInChrome="True"

 

 1 <Window.Template>
 2         <ControlTemplate TargetType="{x:Type Window}">
 3             <AdornerDecorator>
 4                 <Grid x:Name="grid">
 5                     <Grid.RowDefinitions>
 6                         <RowDefinition Height="100" />
 7                         <RowDefinition Height="*" />
 8                     </Grid.RowDefinitions>
 9                     <Grid Grid.Row="0">
10                         <StackPanel
11                             HorizontalAlignment="Right"
12                             Orientation="Horizontal"
13                             WindowChrome.IsHitTestVisibleInChrome="True">
14                             <Button
15                                 Command="{x:Static SystemCommands.MinimizeWindowCommand}"
16                                 Content="最小化" />
17                             <Button
18                                 Command="{x:Static SystemCommands.RestoreWindowCommand}"
19                                 Content="最大化" />
20                             <Button
21                                 Command="{x:Static SystemCommands.CloseWindowCommand}"
22                                 Content="关闭" />
23                         </StackPanel>
24                     </Grid>
25                     <ContentPresenter Grid.Row="1" />
26                 </Grid>
27             </AdornerDecorator>
28             <ControlTemplate.Triggers>
29                 <Trigger Property="WindowState" Value="Maximized">
30                     <Setter TargetName="grid" Property="Margin" Value="8" />
31                 </Trigger>
32             </ControlTemplate.Triggers>
33         </ControlTemplate>
34     </Window.Template>

注意:最大化时存在边界溢出

处理方法:在xaml中编写触发器,当前窗口状态为 WindowState="Maximized" 时,给容器增加margin,margin左右的值为 (SystemParameters.MaximizedPrimaryScreenWidth - SystemParameters.WorkArea.Width)/ 2 ,上下也是同理。

如有更好的方法,希望留下建议。

效果图:

posted @ 2022-08-16 15:15  逸羽澜心  阅读(1584)  评论(1编辑  收藏  举报