67

In my APP I'm using an API of a software that my tool is managing. I've DAL that contain 16 classes, 3 of them are singletons. I've some logic in the .cs files and XAML's off course.

My question is, I see a lot of comments that an app written in WPF should use MVVM, and this will make the code more usable and readable, can I transform my code to be MVVM? what it the actual meaning of MVVM (not Wikipedia or manual definition)?

I also use SQL queries and I read a paper about EF (Entity Framework), can MVVM and EF coexist together in the same project?

2

4 Answers 4

131

The actual meaning of MVVM is: UI is not Data. Data is Data, UI is UI.

This means that you should not develop the application in a way that the program logic (often called business logic) is tightly coupled or dependent on the state of UI components, but instead make it dependent on the state of data items (be it the Model, or the View Model).

For example, in other frameworks (such as winforms), if you have a screen that contains a textbox, and a button, you usually add a click event handler to the button and then read the text from the textbox. in MVVM, the Text property of the TextBox should be bound to a string property in the ViewModel, and the button should be bound to a Command in the ViewModel as well.

This allows for an abstraction of the UI (which is the ViewModel), so that, as I said before, your application logic can be dependent on not the UI but an abstraction of it.

This allows for a huge amount of scalability in the UI and the logic, and also allows for the testability of several aspects of UI behavior because a big portion of the UI behavior is defined in the ViewModel.

There are other aspects of MVVM as well, but the main realization is that.

Edit:

I will add a concrete example of this for completeness of the answer:

1 - Non MVVM WPF:

XAML:

<StackPanel>
   <TextBox x:Name="txtLastName"/>
   <Button Content="Click Me" Click="Button_Click"/>
</StackPanel>

Code behind:

private void Button_Click(object sender, EventArgs e)
{
    //Assuming this is the code behind the window that contains the above XAML.
    var lastname = this.txtLastName.Text; 

    //Here you do some actions with the data obtained from the textbox
}

2 - MVVM WPF:

XAML:

<StackPanel>
   <StackPanel.DataContext>
       <my:MyViewModel/>
   </StackPanel.DataContext>
   <TextBox Text="{Binding LastName}"/>
   <Button Content="Click Me" Command="{Binding MyCommand}"/>
</StackPanel>

ViewModel:

public class MyViewModel
{
    public string LastName { get; set; }

    public Command MyCommand { get; set; }

    public MyViewModel()
    {
        // The command receives an action on the constructor,
        // which is the action to execute when the command is invoked.
        MyCommand = new Command(ExecuteMyCommand); 
    }

    private void ExecuteMyCommand()
    {
        //Only for illustration purposes, not really needed.
        var lastname = this.LastName; 

        //Here you do some actions with the data obtained from the textbox
    }
}

As you can see in the above example, the ViewModel contains no reference at all to the View. Thus, the View could be anything, as long as the {Bindings} are kept in place.

The glue that magically makes them work together is the DataContext Property of WPF UI Elements, which is the object that all bindings will be resolved against.

There are other things, such as the Property Change Notification in the ViewModel to enable two-way bindings, but that is out of the scope of this answer.

Also keep in mind that MVVM is a design pattern, whereas WPF is a framework. MVVM is also being currently applied in other technologies (there is currently a lot of buzz about MVVM for the web, with JavaScript and stuff like that)

I suggest you read the books mentioned in other answers as well as this Tutorial for more WPF-specific aspects.

2
  • One of the best explanation I have seen on the subject. Thanks.
    – nawfal
    Jun 5, 2015 at 13:44
  • I agree. It's on of the best responses on the WPF - MVVM refactoring subject. Thanks!
    – Majak
    Nov 3, 2015 at 9:50
15

My question is, I see a lot of comments that an app written in WPF should use MVVM, and this will make the code more usable and readable, can I transform my code to be MVVM?

There's no requirement that you need to use the MVVM pattern - none. You need to consider the complexity of the app you are building and the development groups skill-set. Generally speaking, if it's a small or small/medium app then MVVM may be over-engineering. If the group's skills/talent aren't a good fit for a separated presentation pattern, then MVVM may not be a good decision.

If done right, then MVVM gives you all the sorts of benefits that you've read about. Conversely, if it's done wrong, then it can be a development and maintanence nightmare - definitely not more readable and usable. From personal experience, I think it's easier to work on a poorly written code-behind app rather than a poorly written MVVM based one.

Sure, you can rewrite your current app to the MVVM pattern. Just remove your code-behind and put it into your view-models, helper classes, repository classes, biz-logic classes, etc. Don't fall into the trap of putting everything into you view-models, creating an MVVM-glorified code-behind.

I also use SQL queries and I read a paper about EF (Entity Framework), can MVVM and EF leave together in the same project?

Sure, they can. Just remember that EF is a data access technology and MVVM is a design pattern. You'll probably use EF in your DAL classes that you mention.

One final thought, if you decide to go down the MVVM route then you should consider using a framework that facilitates it, like Prism. Oh, and be prepared for quite a bit of learning and frustration.

4
  • 1
    I agree with @Big Daddy considering to use a framework, in my case I am working with Caliburn.Micro (I started with Prism but I found it a bit complicated). Just one year ago I was in the same situation than you, and I decided to change to MVVM, the beginning was hard but now all is more logical, clean and ordered, I am enjoying myself :-) Nov 8, 2013 at 15:26
  • I do agree about app size and the purpose of the app (internal testing framework or customer app? etc) do play a big role in the decision. But once the mvvm pattern is learned (prism is wonderful!) Just took a few days writing mvvm with prism in my spare time and I will most likely use it for all of my medium or larger projects now.
    – Josh
    Jan 14, 2015 at 20:58
  • @Josh...It's a great pattern. The thing is, many times small apps become larger then they where intended to be. If MVVM isn't already in place, then we can end up with messy code-base.
    – Big Daddy
    Jan 16, 2015 at 12:21
  • I just want to mention something to support this answer. "MVVM May be over-engineering" This can be true, especially if you're using a framework. However you can slap together the bare bones of an MVVM framework in minutes. Implement a base class with INotifyPropertyChanged and Implement a class which can be used to execute Commands. That is all you REALLY need to build an MVVM/WPF application. For me it has gotten to the point where I will opt to build an MVVM/WPF application over a command line app for quick tests and analysis. Jan 30, 2015 at 15:35
2

I would definitely look into DependencyInjection, using a framework like Unity.

Your Singleton classes could be registered with a DependencyInjection container and injected into constructors of other classes (such as ViewModels). So could other DAL classes which need to be instantiated regularly and injected into classes.

DependencyInjection is the single most important design pattern when developing large enterprise software applications and is applicable for both Client & Server code. MVVM is a nice pattern but won't address the issue of overall application complexity related to dependency coupling.

2

These are mine specific to MVVM

1) Increases the "Blendability" of your views (ability to use Expression Blend to design views). This enables a separation of responsibilities on teams that are lucky enough to have a designer and a programmer... each can work independent of the other.

2) "Lookless" view logic. Views are agnostic from the code that runs behind them, enabling the same view logic to be reused across multiple views or have a view easily retooled or replaced. Seperates concerns between "behavior" and "style".

3) No duplicated code to update views. In code-behind you will see a lot of calls to "myLabel.Text = newValue" sprinkled everywhere. With MVVM you can be assured the view is updated appropriately just by setting the underlying property and all view side-effects thereof.

4) Testability. Since your logic is completely agnostic of your view (no "myLabel.Text" references), unit testing is made easy. You can test the behavior of a ViewModel without involving its view. This also enabled test-driven development of view behavior, which is almost impossible using code-behind.

The other two patterns are really sort of separate in terms of the concerns they address. You can use MVVM with MVP and MVC (most good samples out there do some form of this).

In fact, MVP (w/ a Passive View, rather than a Supervising Controller) is really just a variant of MVVM, in my opinion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.