深入探討WPF窗口不規(guī)則形式實(shí)現(xiàn)技巧
WPF中的窗口實(shí)現(xiàn),在許多應(yīng)用程序中都是比較常用到的。而且根據(jù)開發(fā)人員需求的不同,WPF窗口還可以根據(jù)需求進(jìn)行各種形態(tài)的變化。#t#
在WPF窗口要實(shí)現(xiàn)不規(guī)則形狀的窗口其實(shí)很簡單,首先我們要設(shè)置幾個Window的屬性,如下:
- < Window x:Class="Borderless
Window.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" - >
這里我們設(shè)置了WindowStyle="None",這表示去掉WPF窗口的邊框和標(biāo)題欄;Background="{x:Null}"表示背景為透明,這一步必須做,因?yàn)槟J(rèn)的背景色是白色的;AllowsTransparency="True"是與WindowsStyle.None配合使用的,如果你在此時把WindowStyle="None"去掉,會收到一個錯誤。
在主窗口中,我們可以放入以下一段代碼:
- < Grid>
- < Border CornerRadius="5,5,5,5"
Background="#FF777777"
Height="Auto"> < /Border>- < /Grid>
這表示一個帶有圓弧彎角的矩形。
但這樣是不是就實(shí)現(xiàn)了呢?當(dāng)然不是,現(xiàn)在運(yùn)行WPF窗口你會發(fā)現(xiàn)一些問題——無法拖動、無法關(guān)閉。不過不用擔(dān)心,實(shí)現(xiàn)這些功能并不難,因?yàn)閃indow提供了相應(yīng)的函數(shù)來實(shí)現(xiàn)拖動和關(guān)閉——DragMove和Close。
拖動的話,我們可以為Window添加一個MouseLeftButtonDown的事件處理程序,并在里面調(diào)用DragMove就可以了(不需要任何參數(shù)):
- public void DragWindow
(object sender, Mouse
ButtonEventArgs args)- {
- this.DragMove();
- }
至于關(guān)閉,我們可以添加一個按鈕,然后在Click事件處理程序中調(diào)用Close:
- public void CloseWindow
(object sender, Routed
EventArgs args)- {
- this.Close();
- }
為了讓關(guān)閉按鈕更別致些,我對Button的Template做了重載。到這里就基本完成了WPF窗口的設(shè)置。