basti
basti

Reputation: 2689

Sending Event from ViewModel to calling application

I am implementing a little extension for an existing application. Now I am creating a 'wpf-library' with mvvm and everything seems quite nice at the moment.

Now let's say I have an event to delete some datasets from the underlying Database. I don't want to do this in my extension-app but in the calling-application.

So what I have achieved (and whats working) is that the user clicks on my 'remove' button, the view-model implemented the command and here I am able to fire an event. What I wanted is to send the event out to the calling-application.

My startup-class that the calling-app is able to see now like this:

    public UserControl ViewToShowInContainer { get; private set; }

    public StartMyExtensionApplication(Model.TransportClass dataToWorkWith)
    {
        ViewToShowInContainer = new View.MainView();
        (ViewToShowInContainer.DataContext as VehicleSearchWPF.ViewModel.MyMainViewModel).RemoveSelectStatementFromDB += new EventHandler<SelectStatementRemovedEventArgs>(StartVehicleSearch_RemoveSelectStatementFromDB);
        LocalDataToWorkWith.MapTransportClass(dataToWorkWith);
    }

    void StartVehicleSearch_RemoveSelectStatementFromDB(object sender, SelectStatementRemovedEventArgs e)
    {
        throw new NotImplementedException();
    }

But in my opinien there must be some nicer / cleaner / better method to implement this?

Thanks in advance! :)

Upvotes: 2

Views: 361

Answers (1)

stijn
stijn

Reputation: 35901

This indeed doesn't seem like the right place to use normal events; a couple of other options:

-do not use events but use 'services', imo more clear and more direct while still decoupling. Has the benefit that you can easily test your viewmodel (eg test that executing the Remove command effectively calls Remove on the database) by mocking the database service.

  //a database interface
public interface IDataBase
{
  public void Remove( string entry );
  //etc
}

  //a concrete database
public class SqlDataBase : IDataBase
{
  //implementation of IDataBase
}

  //vm uses an IDataBase
class VehicleSearchViewModel
{
  public VehicleSearchViewModel( IDataBase dataBase );

  private void Remove( string id )
  {
    dataBase.Remove( id );
  }
}

  //so main app can pass it
public StartMyExtensionApplication( .... )
{
  var dataBase = CreateDataBase( .... );
  view.DataContext = new VehicleSearchViewModel( dataBase );
}

-use something like Prism's IEventAggregator

class VehicleSearchViewModel
{
  public VehicleSearchViewModel( IEventAggregator aggr );

  private void Remove( string id )
  {
    aggr.Publish( new RemoveFromDBEvent{ id = id } );
  }
}

public StartMyExtensionApplication( .... )
{
  aggr.Subscribe<RemoveFromDBEvent>( DoRemove );
}

private void DoRemove( RemoveFromDBEvent evt )
{
  dataBase.Remove( evt.id );
}

Upvotes: 1

Related Questions