Building reusable CRUD controls in WPF and MVVM

后端 未结 2 871
长情又很酷
长情又很酷 2021-02-11 07:33

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 produ

2条回答
  •  耶瑟儿~
    2021-02-11 08:24

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

提交回复
热议问题