c# - WPF MVVM 代码背后的最佳实践

标签 c# wpf mvvm code-behind

我是一名学生,正在使用 MVVM 模式通过 WPF 学习 C#。最近我一直在研究我的应用程序的艺术(自定义启动画面),当我不希望它关闭时它不应该关闭。 我一直在网上搜索没有代码隐藏的好方法。不幸的是,几天后我仍然没有找到令人满意的方法。 然后我想到了一种自己做的方法,只需要在我的 View 构造函数中的一行代码的帮助下。它仍然使我的代码可测试并将代码与 View 分离。问题是,有没有更好的方法来做我想做的事情:

我的 ViewModel 界面

public interface IPreventCloseViewModel
{
    bool PreventClose { get; set; }
}

View 的扩展

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;
                                       }
                                   };
        }
    }
}

View 的代码隐藏

public partial class SplashScreen
{
    public SplashScreen()
    {
        InitializeComponent();
        this.PreventCloseViewModel();
    }
}

最佳答案

MVVM 并不意味着您不能使用代码隐藏。

MVVM 意味着您的应用程序逻辑不应绑定(bind)到 UI 元素。

您可以完美地处理隐藏代码中的事件(例如 Window.Closing),并在 ViewModel 中“发送消息”或执行方法以对此使用react。

在这里,您不会通过将事件处理程序放在代码隐藏中来破坏 MVVM。如果您将确定应用程序是否可以在代码中关闭的逻辑放置在后面,那么您将破坏 MVVM。这是应用程序逻辑的责任,应用程序逻辑存在于 ViewModels 中,而不是 Views 中。

关于c# - WPF MVVM 代码背后的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16973400/

相关文章:

WPF mvvm通过命令发送TreeViewItem的绑定(bind)元素

android - 是否能感知observeForever的生命周期?

c# - 有没有办法在C#中获取extern方法的函数指针

c# - 在多线程 C# 应用程序中嵌入 Python

c# - 动态加载程序集的应用程序配置

wpf - 在 WPF 中访问 DataTemplate 中的项目

c# - 构建后消失的用户控件

c# - 如何在我的工具提示上获得更厚的阴影?

c# - 使用 MVVM 在 UWP 中处理 ListView ItemClick 的最佳实践

c# - 将 UserControl 绑定(bind)到自定义 BusyIndi​​cator 控件