技术标签: ui
做了WPF开发多年,一直未曾自己实现一个自定义Window Style,无论是《WPF编程宝典》或是各种博客都建议使用WindowStyle="None"
和 AllowsTransparency="True"
,于是想当然以为这样就可以了。最近来了兴致想自己实现一个,才知道WindowStyle="None"
的方式根本不好用,原因有几点:
光是性能问题就足以放弃WindowStyle="None"
的实现方式,幸好还有使用WindowChrome的实现方式,但一时之间也找不到理想的实现,连MSDN上的文档( WindowChrome Class )都太过时,.NET 4.5也没有SystemParameters2这个类,只好参考一些开源项目(如 Modern UI for WPF )自己实现了。
Window的基本功能如上图所示。注意除了标准的“最小化”、“最大化/还原”、"关闭"按钮外,Icon上单击还应该能打开窗体的系统菜单,双击则直接关闭窗体。
我想实现类似Office 2016的Window效果:阴影、自定义窗体颜色。阴影、动画效果保留系统默认的就可以了,基本上会很耐看。
大多数自定义Window都有圆角,但我并不喜欢,低DPI的情况下只有几个像素组成的圆角通常都不会很圆滑(如下图),所以保留直角。
另外,激活、非激活状态下标题栏颜色变更:
最终效果如下:
首先,为了方便以后的扩展,我定义了一个名为CustomWindow的模板化控件派生自Window。
public class CustomWindow : Window
{
public CustomWindow()
{
DefaultStyleKey = typeof(CustomWindow);
CommandBindings.Add(new CommandBinding(SystemCommands.CloseWindowCommand, CloseWindow));
CommandBindings.Add(new CommandBinding(SystemCommands.MaximizeWindowCommand, MaximizeWindow, CanResizeWindow));
CommandBindings.Add(new CommandBinding(SystemCommands.MinimizeWindowCommand, MinimizeWindow, CanMinimizeWindow));
CommandBindings.Add(new CommandBinding(SystemCommands.RestoreWindowCommand, RestoreWindow, CanResizeWindow));
CommandBindings.Add(new CommandBinding(SystemCommands.ShowSystemMenuCommand, ShowSystemMenu));
}
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
base.OnMouseLeftButtonDown(e);
if (e.ButtonState == MouseButtonState.Pressed)
DragMove();
}
protected override void OnContentRendered(EventArgs e)
{
base.OnContentRendered(e);
if (SizeToContent == SizeToContent.WidthAndHeight)
InvalidateMeasure();
}
#region Window Commands
private void CanResizeWindow(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = ResizeMode == ResizeMode.CanResize || ResizeMode == ResizeMode.CanResizeWithGrip;
}
private void CanMinimizeWindow(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = ResizeMode != ResizeMode.NoResize;
}
private void CloseWindow(object sender, ExecutedRoutedEventArgs e)
{
this.Close();
//SystemCommands.CloseWindow(this);
}
private void MaximizeWindow(object sender, ExecutedRoutedEventArgs e)
{
SystemCommands.MaximizeWindow(this);
}
private void MinimizeWindow(object sender, ExecutedRoutedEventArgs e)
{
SystemCommands.MinimizeWindow(this);
}
private void RestoreWindow(object sender, ExecutedRoutedEventArgs e)
{
SystemCommands.RestoreWindow(this);
}
private void ShowSystemMenu(object sender, ExecutedRoutedEventArgs e)
{
var element = e.OriginalSource as FrameworkElement;
if (element == null)
return;
var point = WindowState == WindowState.Maximized ? new Point(0, element.ActualHeight)
: new Point(Left + BorderThickness.Left, element.ActualHeight + Top + BorderThickness.Top);
point = element.TransformToAncestor(this).Transform(point);
SystemCommands.ShowSystemMenu(this, point);
}
#endregion
}
主要是添加了几个CommandBindings,用于给标题栏上的按钮绑定。
对于WindowChrome,MSDN是这样描述的:
若要自定义窗口,同时保留其标准功能,可以使用WindowChrome类。 WindowChrome类窗口框架的功能分离开来视觉对象,并允许您控制的客户端和应用程序窗口的非工作区之间的边界。
在CustomWindow的DefaultStyle中添加如下Setting:
<Setter Property="WindowChrome.WindowChrome">
<Setter.Value>
<WindowChrome CornerRadius="0"
GlassFrameThickness="1"
UseAeroCaptionButtons="False"
NonClientFrameEdges="None" />
</Setter.Value>
</Setter>
这样除了包含阴影的边框,整个Window的内容就可以由用户定义了。
<Border BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
x:Name="WindowBorder">
<Grid x:Name="LayoutRoot"
Background="{TemplateBinding Background}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid x:Name="PART_WindowTitleGrid"
Grid.Row="0"
Height="26.4"
Background="{TemplateBinding BorderBrush}">
....
</Grid>
<AdornerDecorator Grid.Row="1" KeyboardNavigation.IsTabStop="False">
<ContentPresenter x:Name="MainContentPresenter"
KeyboardNavigation.TabNavigation="Cycle" />
</AdornerDecorator>
<ResizeGrip x:Name="ResizeGrip"
HorizontalAlignment="Right"
VerticalAlignment="Bottom"
Grid.Row="1"
IsTabStop="False"
Visibility="Hidden"
WindowChrome.ResizeGripDirection="BottomRight" />
</Grid>
</Border>
Window的标准布局很简单,大致上就是标题栏和内容。
PART_WindowTitleGrid是标题栏,具体内容下一节再讨论。
ContentPresenter的内容即Window的Client Area的范围。
ResizeGrip是当ResizeMode = ResizeMode.CanResizeWithGrip;
时出现的Window右下角的大小调整手柄,基本上用于提示窗口可以通过拖动边框改调整小。
AdornerDecorator 为可视化树中的子元素提供 AdornerLayer,如果没有它的话一些装饰效果不能显示(例如下图Button控件的Focus效果),Window的 ContentPresenter 外面套个 AdornerDecorator 是 必不能忘的。
<Button x:Name="Minimize"
ToolTip="Minimize"
WindowChrome.IsHitTestVisibleInChrome="True"
Command="{Binding Source={x:Static SystemCommands.MinimizeWindowCommand}}"
ContentTemplate="{StaticResource MinimizeWhite}"
Style="{StaticResource TitleBarButtonStyle}"
IsTabStop="False" />
标题栏上的按钮实现如上,将Command绑定到SystemCommands,并且设置WindowChrome.IsHitTestVisibleInChrome="True"
,标题栏上的内容要设置这个附加属性才能响应鼠标操作。
<Button VerticalAlignment="Center"
Margin="7,0,5,0"
Content="{TemplateBinding Icon}"
Height="{x:Static SystemParameters.SmallIconHeight}"
Width="{x:Static SystemParameters.SmallIconWidth}"
WindowChrome.IsHitTestVisibleInChrome="True"
IsTabStop="False">
<Button.Template>
<ControlTemplate TargetType="{x:Type Button}">
<Image Source="{TemplateBinding Content}" />
</ControlTemplate>
</Button.Template>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<i:InvokeCommandAction Command="{x:Static SystemCommands.ShowSystemMenuCommand}" />
</i:EventTrigger>
<i:EventTrigger EventName="MouseDoubleClick">
<i:InvokeCommandAction Command="{x:Static SystemCommands.CloseWindowCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
标题栏上的Icon也是一个按钮,单机打开SystemMenu,双击关闭Window。Height和Widht的值分别使用了SystemParameters.SmallIconHeight
和SystemParameters.SmallIconWidth
,SystemParameters包含可用来查询系统设置的属性,能使用SystemParameters的地方尽量使用总是没错的。
按钮的样式没实现得很好,这点暂时将就一下,以后改进吧。
<ControlTemplate.Triggers>
<Trigger Property="IsActive"
Value="False">
<Setter Property="BorderBrush"
Value="#FF6F7785" />
</Trigger>
<Trigger Property="WindowState"
Value="Maximized">
<Setter TargetName="Maximize"
Property="Visibility"
Value="Collapsed" />
<Setter TargetName="Restore"
Property="Visibility"
Value="Visible" />
<Setter TargetName="LayoutRoot"
Property="Margin"
Value="7" />
</Trigger>
<Trigger Property="WindowState"
Value="Normal">
<Setter TargetName="Maximize"
Property="Visibility"
Value="Visible" />
<Setter TargetName="Restore"
Property="Visibility"
Value="Collapsed" />
</Trigger>
<Trigger Property="ResizeMode"
Value="NoResize">
<Setter TargetName="Minimize"
Property="Visibility"
Value="Collapsed" />
<Setter TargetName="Maximize"
Property="Visibility"
Value="Collapsed" />
<Setter TargetName="Restore"
Property="Visibility"
Value="Collapsed" />
</Trigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="ResizeMode"
Value="CanResizeWithGrip" />
<Condition Property="WindowState"
Value="Normal" />
</MultiTrigger.Conditions>
<Setter TargetName="ResizeGrip"
Property="Visibility"
Value="Visible" />
</MultiTrigger>
</ControlTemplate.Triggers>
虽然我平时喜欢用VisualState的方式实现模板化控件UI再状态之间的转变,但有时还是Trigger方便快捷,尤其是不需要做动画的时候。
注意当WindowState=Maximized时要将LayoutRoot的Margin设置成7,如果不这样做在最大化时Window边缘部分会被遮蔽,很多使用WindowChrome自定义Window的方案都没有处理这点。
另一点需要注意的是键盘导航。一般来说Window中按Tab键,焦点会在Window的内容间循环,不要让标题栏的按钮获得焦点,也不要让ContentPresenter 的各个父元素获得焦点,所以在ContentPresenter 上设置KeyboardNavigation.TabNavigation="Cycle"
。为了不让标题栏上的各个按钮获得焦点,在各个按钮上还设置了IsTabStop="False"
,
有些人喜欢不止标题栏,按住Window的任何空白部分都可以拖动Window,只需要在代码中添加DragMove即可:
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
base.OnMouseLeftButtonDown(e);
if (e.ButtonState == MouseButtonState.Pressed)
DragMove();
}
索性让Window打开时内容也添加一些动画。我将Silverlight Toolkit的TransitioningContentControl
复制过来,只改了一点动画,并且在OnApplyTemplate()
最后添加了这句:VisualStateManager.GoToState(this, Transition, true);
。最后将Window中的ContentPresenter 替换成这个控件,效果还不错(实际效果挺流畅的,可是GIF看起来不怎么样):
有个比较麻烦的问题,当设置SizeToContent="WidthAndHeight"
,打开Window会出现以下错误。
看上去是内容的Size和Window的Size计算错误,目前的解决方法是在CustomWindow中添加以下代码,简单粗暴,但可能引发其它问题:
protected override void OnContentRendered(EventArgs e)
{
base.OnContentRendered(e);
if (SizeToContent == SizeToContent.WidthAndHeight)
InvalidateMeasure();
}
第一次写Window样式,想不到遇到这么多需要注意的地方。
目前只是个很简单的Demo,没有添加额外的功能,希望对他人有帮助吧。
编码在Window10上完成,只在Windows7上稍微测试了一下,不敢保证兼容性。
如有错漏请指出。
Window Styles and Templates
WindowChrome 类
SystemParameters 类
mahapps.metro
Modern UI for WPF
文章浏览阅读645次。这个肯定是末尾的IDAT了,因为IDAT必须要满了才会开始一下个IDAT,这个明显就是末尾的IDAT了。,对应下面的create_head()代码。,对应下面的create_tail()代码。不要考虑爆破,我已经试了一下,太多情况了。题目来源:UNCTF。_攻防世界困难模式攻略图文
文章浏览阅读2.9k次,点赞3次,收藏10次。偶尔会用到,记录、分享。1. 数据库导出1.1 切换到dmdba用户su - dmdba1.2 进入达梦数据库安装路径的bin目录,执行导库操作 导出语句:./dexp cwy_init/[email protected]:5236 file=cwy_init.dmp log=cwy_init_exp.log 注释: cwy_init/init_123..._达梦数据库导入导出
文章浏览阅读1.9k次。1. 在官网上下载KindEditor文件,可以删掉不需要要到的jsp,asp,asp.net和php文件夹。接着把文件夹放到项目文件目录下。2. 修改html文件,在页面引入js文件:<script type="text/javascript" src="./kindeditor/kindeditor-all.js"></script><script type="text/javascript" src="./kindeditor/lang/zh-CN.js"_kindeditor.js
文章浏览阅读2.3k次,点赞6次,收藏14次。SPI的详情简介不必赘述。假设我们通过SPI发送0xAA,我们的数据线就会变为10101010,通过修改不同的内容,即可修改SPI中0和1的持续时间。比如0xF0即为前半周期为高电平,后半周期为低电平的状态。在SPI的通信模式中,CPHA配置会影响该实验,下图展示了不同采样位置的SPI时序图[1]。CPOL = 0,CPHA = 1:CLK空闲状态 = 低电平,数据在下降沿采样,并在上升沿移出CPOL = 0,CPHA = 0:CLK空闲状态 = 低电平,数据在上升沿采样,并在下降沿移出。_stm32g431cbu6
文章浏览阅读1.2k次,点赞2次,收藏8次。数据链路层习题自测问题1.数据链路(即逻辑链路)与链路(即物理链路)有何区别?“电路接通了”与”数据链路接通了”的区别何在?2.数据链路层中的链路控制包括哪些功能?试讨论数据链路层做成可靠的链路层有哪些优点和缺点。3.网络适配器的作用是什么?网络适配器工作在哪一层?4.数据链路层的三个基本问题(帧定界、透明传输和差错检测)为什么都必须加以解决?5.如果在数据链路层不进行帧定界,会发生什么问题?6.PPP协议的主要特点是什么?为什么PPP不使用帧的编号?PPP适用于什么情况?为什么PPP协议不_接收方收到链路层数据后,使用crc检验后,余数为0,说明链路层的传输时可靠传输
文章浏览阅读587次。软件测试工程师移民加拿大 无证移民,未受过软件工程师的教育(第1部分) (Undocumented Immigrant With No Education to Software Engineer(Part 1))Before I start, I want you to please bear with me on the way I write, I have very little gen...
文章浏览阅读304次。Thinkpad X250笔记本电脑,装的是FreeBSD,进入BIOS修改虚拟化配置(其后可能是误设置了安全开机),保存退出后系统无法启动,显示:secure boot failed ,把自己惊出一身冷汗,因为这台笔记本刚好还没开始做备份.....根据错误提示,到bios里面去找相关配置,在Security里面找到了Secure Boot选项,发现果然被设置为Enabled,将其修改为Disabled ,再开机,终于正常启动了。_安装完系统提示secureboot failure
文章浏览阅读10w+次,点赞93次,收藏352次。1、用strtok函数进行字符串分割原型: char *strtok(char *str, const char *delim);功能:分解字符串为一组字符串。参数说明:str为要分解的字符串,delim为分隔符字符串。返回值:从str开头开始的一个个被分割的串。当没有被分割的串时则返回NULL。其它:strtok函数线程不安全,可以使用strtok_r替代。示例://借助strtok实现split#include <string.h>#include <stdio.h&_c++ 字符串分割
文章浏览阅读2.3k次。1 .高斯日记 大数学家高斯有个好习惯:无论如何都要记日记。他的日记有个与众不同的地方,他从不注明年月日,而是用一个整数代替,比如:4210后来人们知道,那个整数就是日期,它表示那一天是高斯出生后的第几天。这或许也是个好习惯,它时时刻刻提醒着主人:日子又过去一天,还有多少时光可以用于浪费呢?高斯出生于:1777年4月30日。在高斯发现的一个重要定理的日记_2013年第四届c a组蓝桥杯省赛真题解答
文章浏览阅读851次,点赞17次,收藏22次。摘要:本文利用供需算法对核极限学习机(KELM)进行优化,并用于分类。
文章浏览阅读1.1k次。一、系统弱密码登录1、在kali上执行命令行telnet 192.168.26.1292、Login和password都输入msfadmin3、登录成功,进入系统4、测试如下:二、MySQL弱密码登录:1、在kali上执行mysql –h 192.168.26.129 –u root2、登录成功,进入MySQL系统3、测试效果:三、PostgreSQL弱密码登录1、在Kali上执行psql -h 192.168.26.129 –U post..._metasploitable2怎么进入
文章浏览阅读257次。本文将为初学者提供Python学习的详细指南,从Python的历史、基础语法和数据类型到面向对象编程、模块和库的使用。通过本文,您将能够掌握Python编程的核心概念,为今后的编程学习和实践打下坚实基础。_python人工智能开发从入门到精通pdf