1. 程式人生 > 其它 >WPF 的 Window 樣式控制元件模板如何實現關閉後彈窗提示

WPF 的 Window 樣式控制元件模板如何實現關閉後彈窗提示

WPF 使用中,通過自定義 Window 樣式繫結,實現統一的介面風格,像自定義無邊框窗體。如果有這樣的場景,使用者點選窗體上的x試圖關閉窗體,在某種情況下,如資料未儲存,想要彈一個 MessageBox 來提示使用者是否確定關閉。這樣如何實現呢?

下面是我想的一種實現方式,在窗體 XMAL 程式碼中定義一個 bool 靜態資源,關閉時間的後臺程式碼通過判斷它來執行,同時窗體的 behindCode 也可以更改它

Style 樣式中的 ControlTemplate 的一個 x 關閉按鈕用來關閉窗體:

<Button Height="20" Width="20" Content="{StaticResource WindowCloseSymbol}" HorizontalContentAlignment="Center" Margin="2 0 0 0"
                              Style="{StaticResource ResourceKey=CustomWindowMenuBtn}" Click="CustomWindowBtnClose_Click" />

Window 的這個 Style 樣式關閉按鈕 Click 綁定了後臺事件程式碼:

// 關閉
private void CustomWindowBtnClose_Click(object sender, RoutedEventArgs e)
{
    Window win = (Window)((FrameworkElement)sender).TemplatedParent;

    if (win.TryFindResource("CanClose") == null)
    {
        win.Close();
        return;
    }

    if (!(bool)win.FindResource("CanClose"))
    {
        string msg = (string)win.TryFindResource("Message");

        if (msg == null)
        {
            return;
        }

        if (HMessageBoxLib.HMessageBox.Show(msg, "提示", HMessageBoxLib.HMessageBoxButtons.YesNo) != HMessageBoxLib.HMessageboxResult.Yes)
        {
            return;
        }

        win.Close();

        if (win.Owner != null)
            win.Owner.Activate();

        return;
    }

    win.Close();

    if (win.Owner != null)
        win.Owner.Activate();
}

窗體的 XMAL 靜態資源:

<Window.Resources>
    <sys:Boolean x:Key="CanClose" >True</sys:Boolean>
    <sys:String x:Key="Message" >未儲存,是否確定退出?</sys:String>
</Window.Resources>

效果是這樣的:

點選右上的 x 關閉,會有彈窗:

在知道資源位置的情況下,窗體後臺程式碼可以直接通過鍵索引的這樣的方式更改資源的值,這樣可以在關閉視窗之前,更改 Resources["CanClose"]

根據情況是否要彈窗判斷:

Resources["CanClose"] = true;
Resources["Message"] = "確定關閉嗎?";

這的CanClosetrue時,可以直接關閉視窗,不需要彈窗提醒;相反為false時則不能直接關閉窗體,需要彈窗提醒。