在WPF中要实现不规则形状的窗口其实很简单,首先我们要设置几个Window的属性,如下:
<Window x:Class="BorderlessWindow.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="BorderlessWindow" Height="300" Width="300"
WindowStyle="None" Background="{x:Null}" AllowsTransparency="True"
>
这里我们设置了WindowStyle="None",这表示去掉窗口的边框和标题栏;Background="{x:Null}"表示背景为透明,这一步必须做,因为默认的背景色是白色的;AllowsTransparency="True"是与WindowsStyle.None配合使用的,如果你在此时把WindowStyle="None"去掉,会收到一个错误。
在主窗口中,我们可以放入以下一段代码:

<Grid>
<Border CornerRadius="5,5,5,5" Background="#FF777777" Height="Auto">
</Border>
</Grid>
这表示一个带有圆弧弯角的矩形,运行结果如下所示:

但这样是不是就实现了呢?当然不是,现在运行窗口你会发现一些问题——无法拖动、无法关闭。不过不用担心,实现这些功能并不难,因为Window提供了相应的函数来实现拖动和关闭——DragMove和Close。
拖动的话,我们可以为Window添加一个MouseLeftButtonDown的事件处理程序,并在里面调用DragMove就可以了(不需要任何参数):

public void DragWindow(object sender, MouseButtonEventArgs args)
{
this.DragMove();
}
至于关闭,我们可以添加一个按钮,然后在Click事件处理程序中调用Close:

public void CloseWindow(object sender, RoutedEventArgs args)
{
this.Close();
}
最后的实现效果如下:

为了让关闭按钮更别致些,我对Button的Template做了重载(不过这不是重点
)。
完整的实现,大家自己看代码吧。点击这里下载代码。
<Window x:Class="BorderlessWindow.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="BorderlessWindow" Height="300" Width="300"
WindowStyle="None" Background="{x:Null}" AllowsTransparency="True"
>这里我们设置了WindowStyle="None",这表示去掉窗口的边框和标题栏;Background="{x:Null}"表示背景为透明,这一步必须做,因为默认的背景色是白色的;AllowsTransparency="True"是与WindowsStyle.None配合使用的,如果你在此时把WindowStyle="None"去掉,会收到一个错误。
在主窗口中,我们可以放入以下一段代码:

<Grid>
<Border CornerRadius="5,5,5,5" Background="#FF777777" Height="Auto"></Border>
</Grid>这表示一个带有圆弧弯角的矩形,运行结果如下所示:

但这样是不是就实现了呢?当然不是,现在运行窗口你会发现一些问题——无法拖动、无法关闭。不过不用担心,实现这些功能并不难,因为Window提供了相应的函数来实现拖动和关闭——DragMove和Close。
拖动的话,我们可以为Window添加一个MouseLeftButtonDown的事件处理程序,并在里面调用DragMove就可以了(不需要任何参数):

public void DragWindow(object sender, MouseButtonEventArgs args)
{
this.DragMove();
}至于关闭,我们可以添加一个按钮,然后在Click事件处理程序中调用Close:

public void CloseWindow(object sender, RoutedEventArgs args)
{
this.Close();
}最后的实现效果如下:

为了让关闭按钮更别致些,我对Button的Template做了重载(不过这不是重点
)。完整的实现,大家自己看代码吧。点击这里下载代码。

添加至收藏夹