我是一名使用 MVVM 模式通过 WPF 学习 C# 的学生。最近,我一直在研究我的应用程序的艺术(自定义启动屏幕),当我不希望它关闭时,它不应该关闭。
我一直在网上搜索一种无需后台代码即可完成此操作的好方法。不幸的是,几天后我仍然没有找到令人满意的方法。
然后我想到了一种自己做这件事的方法,只需在我的视图构造函数中添加一行代码即可。它仍然使我的代码可测试,并将代码与视图解耦。问题是,有没有更好的方法来做我想做的事情:
我的 ViewModel 界面
public interface IPreventCloseViewModel
{
bool PreventClose { get; set; }
}
视图的扩展
public static class PreventCloseViewModelExtension
{
/// <summary>
/// Use this extension method in the constructor of the view.
/// </summary>
/// <param name="element"></param>
public static void PreventCloseViewModel(this Window element)
{
var dataContext = element.DataContext as IDisposable;
if (dataContext is IPreventCloseViewModel)
{
element.Closing += delegate(object sender, CancelEventArgs args)
{
if (dataContext is IPreventCloseViewModel)
{
args.Cancel = (dataContext as IPreventCloseViewModel).PreventClose;
}
};
}
}
}
视图的隐藏代码
public partial class SplashScreen
{
public SplashScreen()
{
InitializeComponent();
this.PreventCloseViewModel();
}
}
MVVM 并不意味着您不能使用 Code-Behind。
MVVM 意味着您的应用程序逻辑不应与 UI 元素绑定。
您可以完美地处理代码隐藏中的事件(例如Window.Closing
),并“发送消息”或执行 ViewModel 中的方法来对此做出反应。
在这里,您不会通过将事件处理程序放在代码后面来破坏 MVVM。如果您将确定应用程序是否可以关闭的逻辑放在代码后面,那么您将破坏 MVVM。这是应用程序逻辑的责任,应用程序逻辑存在于 ViewModel 中,而不是 View 中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)