WPF自定义标题栏
2023-03-31 10:59:30 时间
往往原有的标题栏无法满足需求,此时就需要进行自定义标题栏。
重新定义Window的Template
首先,需修改WindowChrome的几个属性
CaptionHeight属性值就是自定义标题栏的高,若值低于自定义窗体模板中的标题部分的高,可能会导致,鼠标点击标题栏无法拖动,因为鼠标此时可能不在CaptionHeight范围之内,所以导致无法拖动。
要使没有玻璃框架的自定义窗口,请将 GlassFrameThickness 属性设置为统一值 0
<WindowChrome.WindowChrome> <WindowChrome CaptionHeight="100" UseAeroCaptionButtons="False" GlassFrameThickness="1" /> </WindowChrome.WindowChrome>
自定义窗体模板,此时需要用到占位符ContentPresenter来替窗体工作区的内容进行占位,在非工作区中启用交互式元素需 WindowChrome.IsHitTestVisibleInChrome="True"
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<Window.Template> <ControlTemplate TargetType="{x:Type Window}"> <AdornerDecorator> <Grid x:Name="grid"> <Grid.RowDefinitions> <RowDefinition Height="100" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Grid Grid.Row="0"> <StackPanel HorizontalAlignment="Right" Orientation="Horizontal" WindowChrome.IsHitTestVisibleInChrome="True"> <Button Command="{Binding MinWindowCmd}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}" Content="最小化" /> <Button Command="{Binding MaxWindowCmd}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}" Content="最大化" /> <Button Command="{Binding CloseWindowCmd}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}" Content="关闭" /> </StackPanel> </Grid> <ContentPresenter Grid.Row="1" /> </Grid> </AdornerDecorator> <ControlTemplate.Triggers> <Trigger Property="WindowState" Value="Maximized"> <Setter TargetName="grid" Property="Margin" Value="8" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Window.Template>
ViewModel代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#region 窗口最小化 /// <summary> /// 窗口最小化 /// </summary> private void MinWindow(Window window) { window.WindowState = WindowState.Minimized; } #endregion #region 窗口最大化与还原 /// <summary> /// 窗口最大化与还原 /// </summary> private void MaxWindow(Window window) { window.WindowState = window.WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized; } #endregion #region 窗口关闭 /// <summary> /// 窗口关闭 /// </summary> private void CloseWindow(Window window) { window.Close(); } #endregion
注意:最大化时存在边界溢出
处理方法:在xaml中编写触发器,当前窗口状态为 WindowState="Maximized" 时,给容器增加margin,margin左右的值为 (SystemParameters.MaximizedPrimaryScreenWidth - SystemParameters.WorkArea.Width)/ 2 ,上下也是同理。
如有更好的方法,希望留下建议。
效果图:
相关文章
- 关于.NET玩爬虫这些事
- 为什么 .NET的反射这么慢?
- 在ASP.NET Core中使用百度在线编辑器UEditor
- MVC路由自定义及视图找寻规则
- 构建高性能ASP.NET应用的12点建议
- 你了解AJAX吗?TA不是新编程语言而是WEB应用程序技术
- 从.net转型,聊聊最近一些面试,薪资和想法
- ASP.NET 5 开发者的五个阶段​​
- 让编程更轻松的 7 个 Visual Studio 扩展
- 对 ASP.NET 异步编程的一点理解
- 推荐 7 款好用的 Visual Studio 扩展
- 给ASP.NET MVC及WebApi添加路由优先级
- 10年.NET老程序员推荐的7个开发类工具
- 19 个必须知道的 Visual Studio 快捷键
- 迄今为止最全的.NET技术栈
- .NET中删除空白字符串的10大方法
- 详细的.Net并行编程高级教程--Parallel
- 如何用.NET生成二维码?
- .net程序员工作两年总结
- .NET中删除空白字符串的10大方法