Search code examples
c#wpfxamlmvvmicommand

MVVM Saving in database using ICommand


I have dialog for getting some basic information for saving these in the database on click of a save button. These basic information will be stored in the ViewModel via binding. I handle the database via Entity Framework and so via a DataContext.

private Command.MonitoringTaskCommand objSaveButtonCommand =
    new Command.MonitoringTaskCommand(
        new Action<DataModel.MonitoringTask>(x => {
            DataModel.MonitorContext context = new DataModel.MonitorContext();
            context.MonitoringTasks.Add(x);
            context.SaveChanges();
        }),
        new Func<bool>(() => {
            Debug.WriteLine("Todo: Validate data... ");
            return true;
        }));

I stuck at the save execution.

  • How can I pass the data to the Command?

I know there is the CommandParameter on XAML level, but the data is stored in the ViewModel and can be different from that one in the XAML level.


Solution

  • Data pass from the binding of your command so where your bindings are use CommandParameter to bind your object

    Check this tutorial

    http://www.c-sharpcorner.com/UploadFile/e06010/wpf-icommand-in-mvvm/