我正在WPF中写一个模态对话框。我如何设置一个WPF窗口没有关闭按钮?我仍然希望它的WindowState有一个正常的标题栏。

我找到了ResizeMode、WindowState和WindowStyle,但这些属性都不允许我隐藏关闭按钮,而是显示标题栏,就像在模态对话框中一样。


当前回答

要设置的属性是=> WindowStyle="None"

<Window x:Class="mdaframework.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="Start" Height="350" Width="525" ResizeMode="NoResize"  WindowStartupLocation="CenterScreen" WindowStyle="None">

其他回答

尝试在窗口中添加关闭事件。将此代码添加到事件处理程序中。

e.Cancel = true;

这样可以防止窗口关闭。这与隐藏关闭按钮具有相同的效果。

正如在其他答案中所述,您可以使用WindowStyle="None"来完全删除标题栏。

并且,正如其他答案的评论中所述,这阻止了窗口的可拖动性,因此很难将其从初始位置移动。

但是,你可以通过在窗口的代码后面文件的构造函数中添加一行代码来克服这个问题:

MouseDown += delegate { DragMove(); };

或者,如果你喜欢Lambda语法:

MouseDown += (sender, args) => DragMove();

这使得整个窗口可拖动。窗口中出现的任何交互控件,如按钮,仍将正常工作,不会作为窗口的拖拽句柄。

将WindowStyle属性设置为None,这将隐藏控制框和标题栏。不需要内核调用。

使用这个,从https://stephenhaunts.com/2014/09/25/remove-the-close-button-from-a-wpf-window修改:

using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;

namespace Whatever
{
    public partial class MainMenu : Window
    {
        private const int GWL_STYLE = -16;
        private const int WS_SYSMENU = 0x00080000;

        [DllImport("user32.dll", SetLastError = true)]
        private static extern int GetWindowLongPtr(IntPtr hWnd, int nIndex);

        [DllImport("user32.dll")]
        private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);

        public MainMenu()
        {
             InitializeComponent();
             this.Loaded += new RoutedEventHandler(Window_Loaded);
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            var hwnd = new WindowInteropHelper(this).Handle;
            SetWindowLongPtr(hwnd, GWL_STYLE, GetWindowLongPtr(hwnd, GWL_STYLE) & ~WS_SYSMENU);
        }  

    }
}

这不会隐藏按钮,但会阻止用户通过关闭窗口向前移动。

protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{            
    if (e.Cancel == false)
    {
        Application.Current.Shutdown();
    }
}