WPF中製作無邊框窗體
眾所周知,在WinForm中,如果要製作一個無邊框窗體,可以將窗體的FormBorderStyle屬性設定為None來完成。如果要製作成異形窗體,則需要使用圖片或者使用GDI+自定義繪製。
那麼,在WPF中,我們怎樣製作一個無邊框窗體呢?
答案是將Window的WindowStyle屬性設定為None,即WindowStyle="None" 。如果是非矩形的異形窗體,則需要將背景設為Null,將允許透明設定為True,也就是:Background="{x:Null}" AllowsTransparency="True",可能有些人還希望這個視窗可以拖來拖去,那麼,就還需要設定MouseLeftButtonDown事件,比如:MouseLeftButtonDown="DragWindow",這裡DragWindow由Window的DragMove()來完成。想關閉視窗?那就自己做一個按鈕,然後使用Window本身的Close()方法吧。
下面是效果:這裡右上角有個圓形的X按鈕,是用Button,但將它的樣式設定成了圓角矩形制作的。具體程式碼見下:XAML程式碼:// Window1.xaml<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" MouseLeftButtonDown="DragWindow"
C#程式碼:// Window1.xaml.csusing System;using System.Collections.Generic;using System.Text;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Shapes;
namespace BorderlessWindow{ /// <summary> /// Interaction logic for Window1.xaml /// </summary>
public partial class Window1 : System.Windows.Window {
public Window1() { InitializeComponent(); }
public void DragWindow(object sender, MouseButtonEventArgs args) { this.DragMove(); }
public void CloseWindow(object sender, RoutedEventArgs args) { this.Close(); } }}