Search code examples
wpfeventsmvvmmvpdecoupling

How to further decouple this WPF example toward MVC, MVP, or MVVM?


I've decoupled events in this WPF application in the following way.

What is the best way to continue decoupling?

Shell.xaml:

<Button x:Name="btnProcess"
        Content="Process"
        Margin="10"/>

Bootstrapper.cs:

public void Run()
{
    Shell shell = new Shell(new Customer());
    shell.Show();
}

Shell.xaml.cs:

public Shell(IPerson person)
{
    InitializeComponent();
    btnProcess.Click +=new RoutedEventHandler(person.Process);
}

Customer.cs:

public class Customer : IPerson
{
    public void Process(object sender, RoutedEventArgs e)
    {
        Button theButton = (Button)sender;
        theButton.Content = "Customer processed.";
    }
}

The above code successfully decouples the view Shell from the model Customer:IPerson so that I can swap in e.g. a model Employee:IPerson etc. which handles "Processed" in its own way. That was the first goal.

But now:

  • how do I decouple the Processed method from talking specifically to a Button, so that it could also talk to a MenuItem or a ListView which fires the event in the view and so that it doesn't even have to be an element at all that calls it, e.g. a unit test class?
  • how do I alter other elements of the view other than the sender (Button), e.g. how would I alter the status bar in Shell? I see two ways:
    • I could either build a container which holds all views and inject the container in the Customer upon creation, then the customer can look in the container and manipulate the calling view anyway it wants (although I would have to somehow match the view that sent the event and the view in the container as the same one)
    • I could somehow send the whole view (Window object) to the Model with the eventargs when firing the event, although the Model would need some way of knowing (via interface) what kinds of regions were available to manipulate at runtime
  • How would you continue this application in the direction of a more decoupled design?
  • What pattern is this actually, e.g. MVC, MVP, MVVM? I only see a view (Shell) and a Model (Customer).
    • How would a Presenter fit in?
    • How would a ViewModel fit in?
    • How would a Controller fit in?

Solution

  • I suggest you to implement your event handling using commands instead of classic events. Its very easy in WPF because the command pattern is already implemented, and you can tell all of your UI inputs (button, menu item...) that their command is [name of your command] and handle all of them in one place.