我正在使用MahApps Metro窗口样式,我希望在用户单击窗口的关闭按钮时捕获该事件。
我已将ShutdownMode设置为OnExplicitShutdown,因此我需要在点击该按钮时调用Application.Current.Shutdown();
我该怎么做?
答案 0 :(得分:1)
我相信我也尝试使用WPF和MahApps.Metro做同样的事情(绑定到关闭窗口按钮)。我无法找到明确绑定到该命令的方法,但我能够通过将ShowCloseButton属性设置为false(隐藏它)然后创建我自己的关闭窗口命令按钮并处理逻辑来完成此操作。我的viewmodel。我花了一些时间,但我发现你可以在MahApps.Metro的命令栏中轻松添加你自己的窗口命令控件,只需在你的XAML中添加类似的标记:
<Controls:MetroWindow.WindowCommands>
<Controls:WindowCommands>
<Button Content="X" Command="{Binding CancelCommand}" />
</Controls:WindowCommands>
</Controls:MetroWindow.WindowCommands>
答案 1 :(得分:1)
您需要创建DependencyProperty来处理关闭窗口行为:
<强>的DependencyProperty 强>
namespace MyApp.DependencyProperties
{
public class WindowProperties
{
public static readonly DependencyProperty WindowClosingProperty =
DependencyProperty.RegisterAttached("WindowClosing", typeof(RelayCommand), typeof(WindowProperties), new UIPropertyMetadata(null, WindowClosing));
public static object GetWindowClosing(DependencyObject depObj)
{
return (RelayCommand)depObj.GetValue(WindowClosingProperty);
}
public static void SetWindowClosing(DependencyObject depObj, RelayCommand value)
{
depObj.SetValue(WindowClosingProperty, value);
}
private static void WindowClosing(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
{
var element = (Window)depObj;
if (element != null)
element.Closing += OnWindowClosing;
}
private static void OnWindowClosing(object sender, CancelEventArgs e)
{
RelayCommand command = (RelayCommand)GetWindowClosing((DependencyObject)sender);
command.Execute((Window)sender);
}
}
}
在您的ViewModel
中public RelayCommand WindowClosedCommand { get; set; }
private void WindowClose()
{
Application.Current.Shutdown();
}
在ViewModel的构造函数
中this.WindowCloseCommand = new RelayCommand(WindowClose);
在您的XAML中
<mah:MetroWindow x:Class="MyApp.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mah="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
xmlns:dp="clr-namespace:MyApp.DependencyProperties"
dp:WindowProperties.WindowClosing="{Binding WindowClosedCommand}" />
答案 2 :(得分:1)
由于来自gotapps.net的解决方案对我不起作用,因为我没有找到如何以编程方式执行此操作(我的窗口没有Xaml文件,它只是一个基类)。我找到了另一种解决方法,使用相同的按钮关闭Window,如下所示:
internal class BaseWindow : MetroWindow
{
public BaseWindow()
{
this.Loaded += BaseWindow_Loaded;
}
void BaseWindow_Loaded(object sender, EventArgs e)
{
Button close = this.FindChild<Button>("PART_Close");
close.Click += close_Click;
}
void close_Click(object sender, RoutedEventArgs e)
{
Application.Current.Shutdown(0);
}
}
答案 3 :(得分:0)
您可以使用“关闭”或“关闭”事件
当用户单击“关闭”按钮时,将触发关闭处理程序。这也使您可以控制是否应关闭该应用程序。
类似地,Closed处理程序在窗口关闭之前被触发
<Controls:MetroWindow x:Class="MyClass.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
Title="My Class"
Closing="MainWindow_OnClosing">
</Controls:MetroWindow>