如何?一個不規則形狀的WPF視窗

來源:互聯網
上載者:User

在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做了重載(不過這不是重點)。

完整的實現,大家自己看代碼吧。點擊這裡下載代碼。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.