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

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


当前回答

You may run into the need to toggle the window state depending on what page or user control is currently being displayed. (Yes, this is an unusual scenario, but it can happen. In our case we have a user control in our application that is displayed on an external touch screen for customers to interact with. We don't want our customers to have touch access to close the screen. But the rest of the application uses standard windows frames.) To do this from the code behind of the page or user control. Note: You must run it from the Loaded event not the constructor because the control hasn't been populated in the constructor and it will throw an exception.

// To toggle it off
Window.GetWindow(this).WindowStyle = WindowStyle.None;

// To turn it back on toggle it off
Window.GetWindow(this).WindowStyle = WindowStyle.SingleBorderWindow;

其他回答

XAML 代码

<Button Command="Open" Content="_Open">
    <Button.Style>
        <Style TargetType="Button">
            <Style.Triggers>
                <Trigger Property="IsEnabled" Value="False">
                    <Setter Property="Visibility" Value="Collapsed" />
                </Trigger>
            </Style.Triggers>
        </Style>
     </Button.Style>
</Button>

应该工作

编辑-在你的瞬间,这个线程展示了如何做到这一点,但我不认为窗口有一个属性来获得你想要的而不失去正常的标题栏。

编辑2 这个线程展示了一种方法,但你必须将自己的风格应用到系统菜单,它展示了一种方法,你可以这样做。

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

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

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

WPF没有一个内置的属性来隐藏标题栏的关闭按钮,但是你可以用几行P/Invoke来做到这一点。

首先,将这些声明添加到Window类中:

private const int GWL_STYLE = -16;
private const int WS_SYSMENU = 0x80000;
[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);

然后把下面的代码放到Window的Loaded事件中:

var hwnd = new WindowInteropHelper(this).Handle;
SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU);

这样就没有关闭按钮了。你也不会在标题栏的左边有一个窗口图标,这意味着没有系统菜单,即使你右键单击标题栏——它们都在一起。

重要提示:所有这些都是隐藏按钮。用户仍然可以关闭窗口!如果用户按下Alt+F4,或者通过任务栏关闭应用程序,窗口仍然会关闭。

如果你不想让窗口在后台线程完成之前关闭,那么你也可以覆盖OnClosing并将Cancel设置为true,就像Gabe建议的那样。

在寻找了很多答案之后,我想出了这个简单的解决方法,我将在这里分享,希望它能帮助到其他人。

我设置WindowStyle=0x10000000。

这设置了窗口样式的WS_VISIBLE (0x10000000)和WS_OVERLAPPED (0x0)值。"Overlapped"是显示标题栏和窗口边框的必要值。通过从我的样式值中删除WS_MINIMIZEBOX (0x20000)、WS_MAXIMIZEBOX (0x10000)和WS_SYSMENU (0x80000)值,标题栏中的所有按钮都被删除了,包括关闭按钮。