![]() |
火星上的油条 · Minecraft生存指南专题:村民特辑 - 知乎· 1 年前 · |
![]() |
完美的板栗 · Mysql union all ...· 1 年前 · |
![]() |
礼貌的高山 · MySQL :: MySQL 8.0 ...· 1 年前 · |
![]() |
慷慨大方的碗 · 关于js中return ...· 1 年前 · |
![]() |
踏实的汉堡包 · f# - FSharp.Data ...· 1 年前 · |
我希望处理窗口的
Closing
事件(当用户单击右上角的'X‘按钮时),以便最终显示确认消息或/和取消关闭。
我知道如何在代码隐藏中做到这一点:订阅窗口的
Closing
事件,然后使用
CancelEventArgs.Cancel
属性。
但是我使用的是MVVM,所以我不确定这是不是一个好的方法。
我认为最好的方法是将
Closing
事件绑定到我的ViewModel中的
Command
。
我试过了:
<i:Interaction.Triggers>
<i:EventTrigger EventName="Closing">
<cmd:EventToCommand Command="{Binding CloseCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
在我的ViewModel中有一个关联的
RelayCommand
,但是它不工作(命令的代码不会被执行)。
发布于 2011-12-06 18:11:36
这个选项更简单,也许更适合你。在视图模型构造函数中,您可以订阅主窗口关闭事件,如下所示:
Application.Current.MainWindow.Closing += new CancelEventHandler(MainWindow_Closing);
void MainWindow_Closing(object sender, CancelEventArgs e)
//Your code to handle the event
}
万事如意。
发布于 2014-09-25 15:18:16
如果你不想了解ViewModel中的窗口(或它的任何事件),根据MVVM模式,这里有一个答案。
public interface IClosing
/// <summary>
/// Executes when window is closing
/// </summary>
/// <returns>Whether the windows should be closed by the caller</returns>
bool OnClosing();
}
在ViewModel中添加接口和实现
public bool OnClosing()
bool close = true;
//Ask whether to save changes och cancel etc
//close = false; //If you want to cancel close
return close;
}
在窗口中,我添加了关闭事件。此代码隐藏不会破坏MVVM模式。视图可以知道视图模型!
void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
IClosing context = DataContext as IClosing;
if (context != null)
e.Cancel = !context.OnClosing();
}
发布于 2014-11-07 01:56:07
发问者应该使用STAS answer,但对于使用prism而不使用galasoft/mvvmlight的读者,他们可能想要尝试我使用的:
在顶部的窗口或用户控件等定义中,定义名称空间:
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
就在这个定义之下:
<i:Interaction.Triggers>
<i:EventTrigger EventName="Closing">
![]() |
火星上的油条 · Minecraft生存指南专题:村民特辑 - 知乎 1 年前 |