首先示範 Popup 彈窗元件
在 XAML 裡新增一個按鈕,點擊按鈕喚出 Popup;同時宣告 Popup 容器,預設為隱藏狀態,僅點擊按鈕後才顯示。
<StackPanel Spacing="24" VerticalAlignment="Top">
<!-- 原生 Popup 根容器 -->
<Popup x:Name="MainPopup" Width="320" Height="180">
<Border Background="White" BorderBrush="Gray" BorderThickness="1" CornerRadius="8" Padding="16">
<StackPanel Spacing="12">
<TextBlock Text="自訂彈窗內容" FontSize="18"/>
<TextBlock Text="這是底層原生 Popup 容器"/>
<Button Content="關閉彈窗" Click="BtnClosePopup_Click"/>
</StackPanel>
</Border>
</Popup>
<Button Content="開啟原生 Popup 容器" Click="BtnOpenPopup_Click" HorizontalAlignment="Left"
ToolTipService.ToolTip="開啟底層彈窗層"/>
</StackPanel>Code language: HTML, XML (xml)
接著實作按鈕點擊事件 BtnOpenPopup_Click,邏輯為開啟彈窗。<Popup x:Name="MainPopup" Width="320" Height="180"> ...</Popup> 用來建立浮動彈窗,預設關閉;內部放置按鈕 <Button Content="關閉彈窗" Click="BtnClosePopup_Click"/>,點擊該按鈕即可關閉所屬 Popup。
按下 F12,自動產生兩個按鈕點擊事件函式
.H 標頭檔
#pragma once
#include "MainWindow.g.h"
namespace winrt::AppWinui::implementation
{
struct MainWindow : MainWindowT<MainWindow>
{
public:
MainWindow();
int32_t MyProperty();
void MyProperty(int32_t value);
void BtnOpenPopup_Click(winrt::Windows::Foundation::IInspectable const& sender, winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);
void BtnClosePopup_Click(winrt::Windows::Foundation::IInspectable const& sender, winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);
};
}
namespace winrt::AppWinui::factory_implementation
{
struct MainWindow : MainWindowT<MainWindow, implementation::MainWindow>
{
};
}
Code language: C++ (cpp)
#include "pch.h"
#include "MainWindow.xaml.h"
#if __has_include("MainWindow.g.cpp")
#include "MainWindow.g.cpp"
#endif
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.Globalization.h>
#include <winrt/Windows.UI.h> //Windows::UI::Colors
// 全域命名空間別名,解決類別找不到、RoutedEventArgs 未定義錯誤
using namespace winrt;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Microsoft::UI::Xaml;
using namespace Microsoft::UI::Xaml::Controls;
using namespace Microsoft::UI::Xaml::Controls::Primitives;
// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.
namespace winrt::AppWinui::implementation
{
int32_t MainWindow::MyProperty()
{
throw hresult_not_implemented();
}
void MainWindow::MyProperty(int32_t /* value */)
{
throw hresult_not_implemented();
}
MainWindow::MainWindow()
{
InitializeComponent();
}
}
void winrt::AppWinui::implementation::MainWindow::BtnOpenPopup_Click(winrt::Windows::Foundation::IInspectable const& sender, winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e)
{
MainPopup().IsOpen(true);
}
void winrt::AppWinui::implementation::MainWindow::BtnClosePopup_Click(winrt::Windows::Foundation::IInspectable const& sender, winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e)
{
MainPopup().IsOpen(false);
}
Code language: C++ (cpp)
WinUI 3 C++ 控制項教學 – 浮動彈窗(Popup 通知視窗)
Previous: WinUI 3 C++ 控制項教學 – 導覽與分頁標籤