在 WPF 中,如果想做一个背景透明的异形窗口,基本上都要设置WindowStyle="None"
、AllowsTransparency="True"
这两个属性。如果不想自定义窗口样式,还需要设置Background="Transparent"
。这样的设置会让窗口变成 Layered Window,WPF 在这种类型窗口上的渲染性能是非常糟糕的。
本文介绍如何使用WindowChrome
而不设置AllowsTransparency="True"
制作背景透明的异形窗口,这可以避免异形窗口导致的低渲染性能。
如何实现
要实现这种背景透明的异形窗口,需要为窗口设置以下三个属性:
WindowStyle="None"
ResizeMode="CanMinimize"
或ResizeMode="NoResize"
WindowChrome.GlassFrameThickness="-1"
或设置为其他较大的正数(可自行尝试设置之后的效果)
如下就是一个最简单的例子,最关键的三个属性我已经高亮标记出来了。
<Window x:Class="Walterlv.Demo.MainWindow"xmlns="/winfx//xaml/presentation"xmlns:x="/winfx//xaml"++WindowStyle="None" ResizeMode="CanMinimize"Title="walterlv demo" Height="450" Width="800">++<WindowChrome.WindowChrome>++<WindowChrome GlassFrameThickness="-1" />++</WindowChrome.WindowChrome><Window.Template><ControlTemplate TargetType="Window"><Border Padding="64" Background="Transparent"><Border CornerRadius="16" Background="White"><Border.Effect><DropShadowEffect BlurRadius="64" /></Border.Effect><ContentPresenter ClipToBounds="True" /></Border></Border></ControlTemplate></Window.Template><Grid><TextBlock FontSize="20" Foreground="#0083d0"TextAlignment="Center" VerticalAlignment="Center"><Run Text="欢迎访问吕毅的博客" /><LineBreak /><Run Text="" FontSize="64" FontWeight="Light" /></TextBlock></Grid></Window>