Building reusable CRUD controls in WPF and MVVM

2020-06-06 07:02发布

问题:

I am building an WPF Prism MVVM application.

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.

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.

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

回答1:

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
    }

}


回答2:

Look at this generic control WPFCrudControl, may be useful for you.

A generic WPF CrudControl implemented based on the MVVM pattern. It gives a huge productivity boost for straightforward CRUD operations (Add, Edit, Delete, Validate, Listing with sorting, paging and searching). The control abstracts both the UI and business logic, so it requires relatively minimal coding effort, while keeping it possible to customize its behavior.



标签: wpf mvvm Prism