我该如何在WinUI 3中移除关闭按钮?
WinUI 3应用程序截图:
WinUI 3应用程序截图:
![1](https://istack.dev59.com/Ae56c.webp)
this.ExtendsContentIntoTitleBar = true;
时,右上角的菜单按钮(最大化、最小化和关闭)会使用常见的WinUI元素进行模拟。这可以在Debug->Windows->Live Visual Tree工具窗口中观察到。这是我的程序的屏幕截图。
Visual Tree ScreenShot
请注意,在Window xaml文件中声明的根元素是ClientAreaPresenter
的子元素。模拟的按钮位于TitleBarMinMaxCloseContainer
下面。Microsoft.UI.Xaml.Media.VisualTreeHelper.GetParent()
获取关闭按钮元素Visibility
属性设置为Visibility.Collapsed
。(但这可能看起来不太好。我个人建议同时隐藏所有按钮)。public sealed partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
this.ExtendsContentIntoTitleBar = true; //Hides the default system titlebar.
}
//Visual tree may not have been loaded yet at Ctor.
//It's suggested registering Loaded event of the root element of the window.
private void RootGrid_Loaded(object sender, RoutedEventArgs e)
{
//Gets the close button element. Refer to the Visual Tree.
var contentPresenter = VisualTreeHelper.GetParent(this.Content);
var layoutRoot = VisualTreeHelper.GetParent(contentPresenter);
var titleBar = VisualTreeHelper.GetChild(layoutRoot, 1) as Grid;
var buttonContainer = VisualTreeHelper.GetChild(titleBar, 0) as Grid;
var closeButton = VisualTreeHelper.GetChild(buttonContainer,2) as Button;
if (closeButton != null)
{
closeButton.Visibility = Visibility.Collapsed; //Hides the button.
}
}
}
buttonContainer
的Visibility
属性即可。还可以通过设置RenderTransform
使其超出窗口渲染区域来实现隐藏效果。
然而,这种方法没有文档记录,所以它的兼容性取决于框架的可视树实现。在某些情况下,应用程序在关闭窗口时可能会抛出异常。
RenderTransform
而不是Visibility
,因为Visibility.Collapsed
有时无法阻止点击按钮。titleBar.RenderTransform = new TranslateTransform() { X = 200 }
(这里的titleBar
是先前获取的元素)。 - undefinedMainWindow.xaml.cs
using Microsoft.UI;
using Microsoft.UI.Xaml;
using Microsoft.UI.Windowing;
namespace WinUI3
{
public sealed partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
GetAppWindowAndPresenter();
_apw.IsShownInSwitchers = false;
_presenter.SetBorderAndTitleBar(false, false);
}
private void myButton_Click(object sender, RoutedEventArgs e)
{
myButton.Content = "Clicked";
this.Close();
}
public void GetAppWindowAndPresenter()
{
var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
WindowId myWndId = Win32Interop.GetWindowIdFromWindow(hWnd);
_apw = AppWindow.GetFromWindowId(myWndId);
_presenter = _apw.Presenter as OverlappedPresenter;
}
private AppWindow _apw;
private OverlappedPresenter _presenter;
}
}