在 WPF 和 MVVM 中构建可重用的 CRUD 控件 [英] Building reusable CRUD controls in WPF and MVVM

查看:44
本文介绍了在 WPF 和 MVVM 中构建可重用的 CRUD 控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个 WPF Prism MVVM 应用程序.

I am building an WPF Prism MVVM application.

此应用程序将包含许多 CRUD 窗口.

This application will contain a lot of CRUD windows.

我想优化该窗口的功能(并减少生成的代码量).

I want to optimize the features (and reduce the amount of produced code) of that windows.

我已经使用了一种方法,在该方法中我创建了一个母版页",它具有默认功能并包含一个保留区域,用于注入"可能属于特定实体的不同子控件.我正在尝试在 this question 中学习如何在 WPF 中执行此操作.

I have already used an approach in which I created a "master page" that had the default features and contained a reserved region for "injecting" different subcontrols that could belong to specific entities. I am trying to learn how to do this in WPF in this question.

但我想知道的是:使用 WPF 和 MVVM(或控件)完成此操作的模式是什么?

But what I want to know is: what's the pattern for accomplishing this using WPF and MVVM (or control)?

推荐答案

构建一个接口,您的所有 CRUD ViewModel 都将从中继承该接口,并让您的通用 ViewModel 使用该接口执行 CRUD 操作

Build an interface which all your CRUD ViewModels will inherit from, and have your generic ViewModel use the interface to execute CRUD operations

以下是界面和类的外观示例:

Here's an example of how the interface and classes might look:

// Generic interface
public interface IGenericViewModel
{
    bool Add();
    bool Save();
    bool Delete();
}

// Generic CRUD ViewModel
public class GenericViewModel
{
    public IGenericViewModel ObjectViewModel { get; set; }

    public RelayCommand AddCommand { get ; }
    public RelayCommand SaveCommand { get ; }
    public RelayCommand DeleteCommand { get ; }

    void Add()
    {
        ObjectViewModel.Add();
    }

    void Save()
    {
        ObjectViewModel.Save();
    }

    void Delete()
    {
        ObjectViewModel.Delete();
    }
}

// Specific object ViewModel used by generic CRUD ViewModel
public class CustomerViewModel : ViewModelBase, IGenericViewModel
{

    bool IGenericViewModel.Add()
    {
        // Add logic
    }

    bool IGenericViewModel.Save()
    {
        // Save logic
    }

    bool IGenericViewModel.Delete()
    {
        // Delete object
    }

}

这篇关于在 WPF 和 MVVM 中构建可重用的 CRUD 控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆