A Simple MVVM Example

In my opinion, if you are using WPF or Silverlight you should be using the MVVM design pattern. It is perfectly suited to the technology and allows you to keep your code clean and easy to maintain.

The problem is, there are a lot of online resources for MVVM, each with their own way of implementing the design pattern and it can be overwhelming. I would like to present MVVM in the simplest way possible using just the basics.

So lets start at the beginning.

MVVM

MVVM is short for Model-View-ViewModel.

Models are simple class objects that hold data. They should only contain properties and property validation. They are not responsible for getting data, saving data, click events, complex calculations, business rules, or any of that stuff.

Views are the UI used to display data. In most cases, they can be DataTemplates which is simply a template that tells the application how to display a class. It is OK to put code behind your view IF that code is related to the View only, such as setting focus or running animations.

ViewModels are where the magic happens. This is where the majority of your code-behind goes: data access, click events, complex calculations, business rules validation, etc. They are typically built to reflect a View. For example, if a View contains a ListBox of objects, a Selected object, and a Save button, the ViewModel will have an ObservableCollection ObectList, Model SelectedObject, and ICommand SaveCommand.

MVVM Example

I’ve put together a small sample showing these 3 layers and how they relate to each other. You’ll notice that other than property/method names, none of the objects need to know anything about the others. Once the interfaces have been designed, each layer can be built completely independent of the others.

Sample Model

For this example I’ve used a Product Model. You’ll notice that the only thing this class contains is properties and change notification code.

Usually I would also implement IDataErrorInfo here for property validation, however I have left this out for now.

    public class ProductModel : ObservableObject
    {
        #region Fields

        private int _productId;
        private string _productName;
        private decimal _unitPrice;

        #endregion // Fields

        #region Properties

        public int ProductId
        {
            get { return _productId; }
            set
            {
                if (value != _productId)
                {
                    _productId = value;
                    OnPropertyChanged("ProductId");
                }
            }
        }

        public string ProductName
        {
            get { return _productName; }
            set
            {
                if (value != _productName)
                {
                    _productName = value;
                    OnPropertyChanged("ProductName");
                }
            }
        }

        public decimal UnitPrice
        {
            get { return _unitPrice; }
            set
            {
                if (value != _unitPrice)
                {
                    _unitPrice = value;
                    OnPropertyChanged("UnitPrice");
                }
            }
        }

        #endregion // Properties
    }

The class inherits from ObservableObject, which is a custom class I use to avoid having to rewrite the property change notification code repeatedly. I would actually recommend looking into Microsoft PRISM’s NotificationObject  or MVVM Light’s ViewModelBase which does the same thing once you are comfortable with MVVM, but for now I wanted to keep 3rd party libraries out of this and to show the code.

    public abstract class ObservableObject : INotifyPropertyChanged
    {
        #region INotifyPropertyChanged Members

        /// <summary>
        /// Raised when a property on this object has a new value.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Raises this object's PropertyChanged event.
        /// </summary>
        /// <param name="propertyName">The property that has a new value.</param>
        protected virtual void OnPropertyChanged(string propertyName)
        {
            this.VerifyPropertyName(propertyName);

            if (this.PropertyChanged != null)
            {
                var e = new PropertyChangedEventArgs(propertyName);
                this.PropertyChanged(this, e);
            }
        }

        #endregion // INotifyPropertyChanged Members

        #region Debugging Aides

        /// <summary>
        /// Warns the developer if this object does not have
        /// a public property with the specified name. This
        /// method does not exist in a Release build.
        /// </summary>
        [Conditional("DEBUG")]
        [DebuggerStepThrough]
        public virtual void VerifyPropertyName(string propertyName)
        {
            // Verify that the property name matches a real,
            // public, instance property on this object.
            if (TypeDescriptor.GetProperties(this)[propertyName] == null)
            {
                string msg = "Invalid property name: " + propertyName;

                if (this.ThrowOnInvalidPropertyName)
                    throw new Exception(msg);
                else
                    Debug.Fail(msg);
            }
        }

        /// <summary>
        /// Returns whether an exception is thrown, or if a Debug.Fail() is used
        /// when an invalid property name is passed to the VerifyPropertyName method.
        /// The default value is false, but subclasses used by unit tests might
        /// override this property's getter to return true.
        /// </summary>
        protected virtual bool ThrowOnInvalidPropertyName { get; private set; }

        #endregion // Debugging Aides
    }

In addition to the INotifyPropertyChanged methods, there is also a debug method to validate the PropertyName. This is because the PropertyChange notification gets passed in as a String, and I have caught myself forgetting to change this string when I change the name of a Property.

NoteThe PropertyChanged notification exists to alert the View that a value has changed so it knows to update. I have seen suggestions to drop it from the Model and to expose the Model’s properties to the View from the ViewModel instead of the Model, however I find in most cases this complicates things and requires extra coding. Exposing the Model to the View via the ViewModel is much simpler, although either method is valid.

Sample ViewModel

I am doing the ViewModel next because I need it before I can create the View. This should contain everything the User would need to interact with the page. Right now it contains 4 properties: a ProductModel, a GetProduct command, a SaveProduct command, an a ProductId used for looking up a product.

    public class ProductViewModel : ObservableObject
    {
        #region Fields

        private int _productId;
        private ProductModel _currentProduct;
        private ICommand _getProductCommand;
        private ICommand _saveProductCommand;

        #endregion

        #region Public Properties/Commands

        public ProductModel CurrentProduct
        {
            get { return _currentProduct; }
            set
            {
                if (value != _currentProduct)
                {
                    _currentProduct = value;
                    OnPropertyChanged("CurrentProduct");
                }
            }
        }

        public ICommand SaveProductCommand
        {
            get
            {
                if (_saveProductCommand == null)
                {
                    _saveProductCommand = new RelayCommand(
                        param => SaveProduct(),
                        param => (CurrentProduct != null)
                    );
                }
                return _saveProductCommand;
            }
        }

        public ICommand GetProductCommand
        {
            get
            {
                if (_getProductCommand == null)
                {
                    _getProductCommand = new RelayCommand(
                        param => GetProduct(),
                        param => ProductId > 0
                    );
                }
                return _getProductCommand;
            }
        }

        public int ProductId
        {
            get { return _productId; }
            set
            {
                if (value != _productId)
                {
                    _productId = value;
                    OnPropertyChanged("ProductId");
                }
            }
        }

        #endregion

        #region Private Helpers

        private void GetProduct()
        {
            // You should get the product from the database
            // but for now we'll just return a new object
            ProductModel p = new ProductModel();
            p.ProductId = ProductId;
            p.ProductName = "Test Product";
            p.UnitPrice = 10.00;
            CurrentProduct = p;
        }

        private void SaveProduct()
        {
            // You would implement your Product save here
        }

        #endregion
    }

There is another new class here: the RelayCommand. This is essential for MVVM to work. It is a command that is meant to be executed by other classes to run code in this class by invoking delegates. Once again, I’d recommend checking out the MVVM Light Toolkit’s version of this command when you are more comfortable with MVVM, but I wanted to keep this simple so have included this code here.

    /// <summary>
    /// A command whose sole purpose is to relay its functionality to other
    /// objects by invoking delegates. The default return value for the
    /// CanExecute method is 'true'.
    /// </summary>
    public class RelayCommand : ICommand
    {
        #region Fields

        readonly Action<object> _execute;
        readonly Predicate<object> _canExecute;

        #endregion // Fields

        #region Constructors

        /// <summary>
        /// Creates a new command that can always execute.
        /// </summary>
        /// <param name="execute">The execution logic.</param>
        public RelayCommand(Action<object> execute)
            : this(execute, null)
        {
        }

        /// <summary>
        /// Creates a new command.
        /// </summary>
        /// <param name="execute">The execution logic.</param>
        /// <param name="canExecute">The execution status logic.</param>
        public RelayCommand(Action<object> execute, Predicate<object> canExecute)
        {
            if (execute == null)
                throw new ArgumentNullException("execute");

            _execute = execute;
            _canExecute = canExecute;
        }

        #endregion // Constructors

        #region ICommand Members

        [DebuggerStepThrough]
        public bool CanExecute(object parameters)
        {
            return _canExecute == null ? true : _canExecute(parameters);
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public void Execute(object parameters)
        {
            _execute(parameters);
        }

        #endregion // ICommand Members
    }

Sample View

And now the Views. These are DataTemplates which define how a class should be displayed to the User. There are many ways to add these templates to your application, but the simplest way is to just add them to the startup window’s Resources.

<Window.Resources>
    <DataTemplate DataType="{x:Type local:ProductModel}">
        <Border BorderBrush="Black" BorderThickness="1" Padding="20">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition />
                    <ColumnDefinition />
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition />
                    <RowDefinition />
                </Grid.RowDefinitions>

                <TextBlock Grid.Column="0" Grid.Row="0"  Text="ID" VerticalAlignment="Center" />
                <TextBox Grid.Row="0" Grid.Column="1"  Text="{Binding ProductId}" />

                <TextBlock Grid.Column="0" Grid.Row="1"  Text="Name" VerticalAlignment="Center" />
                <TextBox Grid.Row="1" Grid.Column="1"  Text="{Binding ProductName}" />

                <TextBlock Grid.Column="0" Grid.Row="2"  Text="Unit Price" VerticalAlignment="Center" />
                <TextBox Grid.Row="2" Grid.Column="1"  Text="{Binding UnitPrice}" />

            </Grid>
        </Border>
    </DataTemplate>

    <DataTemplate DataType="{x:Type local:ProductViewModel}">
        <DockPanel Margin="20">
            <DockPanel DockPanel.Dock="Top">
                <TextBlock Margin="10,2" DockPanel.Dock="Left" Text="Enter Product Id" VerticalAlignment="Center" />

                <TextBox Margin="10,2" Width="50" VerticalAlignment="Center" Text="{Binding Path=ProductId, UpdateSourceTrigger=PropertyChanged}" />

                <Button Content="Save Product" DockPanel.Dock="Right" Margin="10,2" VerticalAlignment="Center"
                        Command="{Binding Path=SaveProductCommand}" Width="100" />

                <Button Content="Get Product" DockPanel.Dock="Right" Margin="10,2" VerticalAlignment="Center"
                        Command="{Binding Path=GetProductCommand}" IsDefault="True" Width="100" />
            </DockPanel>

            <ContentControl Margin="20,10" Content="{Binding Path=CurrentProduct}" />
        </DockPanel>
    </DataTemplate>
</Window.Resources>

The View defines two DataTemplates: one for the ProductModel, and one for the ProductViewModel. You’ll need to add a namespace reference  to the Window definition pointing to your Views/ViewModels so you can define the DataTypes. Each DataTemplate only binds to properties belonging to the class it is made for.

In the ViewModel template, there is a ContentControl that is bound to ProductViewModel.CurrentProduct. When this control tries to display the CurrentProduct, it will use the ProductModel DataTemplate.

Starting the Sample

And finally, to start the application add the following on startup:

MainWindow app = new MainWindow();
ProductViewModel viewModel = new ProductViewModel();
app.DataContext = viewModel;
app.Show();

This is found in the code behind the startup file – usually App.xaml.cs.

This creates your Window (the one with the DataTemplates defined in Window.Resources), creates a ViewModel, and it sets the Window’s DataContext to the ViewModel.

And there you have it. A basic look at MVVM.

UPDATE
Sample code can be found here.

Notes

There are many other ways to do the things shown here, but I wanted to give you a good starting point before you start diving into the confusing world of MVVM.

The important thing to remember about using MVVM is your Forms, Pages, Buttons, TextBoxes, etc (the Views) are NOT your application. Your ViewModels are. The Views are merely a user-friendly way to interact with your ViewModels.

So if you want to change pages, you should not be changing pages in the View, but instead you should be setting something like the AppViewModel.CurrentPage = YourPageViewModel. If you want to run a Save method, you don’t put that behind a button’s Click event, but rather bind the Button.Command to a ViewModel’s ICommand property.

I started with  Josh Smith’s article on MVVM, which was a good read but for a beginner like me, some of these concepts flew right over my head.

I’ve never done a blog or tutorial before, but I noticed there is a lot of confusion about what MVVM is and how to use it. Since I struggled through the maze of material online to figure out what MVVM is and how its used, I thought I’d try and write a simpler explanation. I hope this clarifies things a bit and doesn’t make it worse :)

>> Next – Navigation with MVVM

45 Responses to A Simple MVVM Example

  1. Davros says:

    This looks great, is there sample code I can download to see it in action?
    Thank you.

  2. Thanks, Rachel!
    I’ve been berating myself for being a doofus, not grokking MVVM. This helps.

  3. I think I’ve got a valid (no pun intended) problem with the code in the article.

    I’m getting the err msg, “‘SimpleMVVMExample.Model.ProductModel’ does not contain a definition for ‘IsValid’ and no extension method ‘IsValid’ accepting a first argument of type ‘SimpleMVVMExample.Model.ProductModel’ could be found (are you missing a using directive or an assembly reference?)”

    In the article, “IsValid” only appears once – on that line where I’m getting the err msg. What to do/how to solve this?

    • Rachel says:

      Sorry about that, my original sample had the Model’s implementing IDataErrorInfo and doing some validation. I left that out for simplicity, and forgot to remove the IsVaild reference. Thanks for catching that.

  4. Rohit Khare says:

    Hi Rachel,

    Just a right time. I am planning to scale my old inventory application to a WPF app. and was looking for few easy samples on MVVM. Most of the MVVM explanation on the net uses very cryptic language that is hard to understand for beginners.

    Thanks for the simple explanation and little sample.

  5. Mark Wiskochil says:

    Hi Rachel, This is a great article, I just have one question. When you run this app, there is textbox validation going on. Where is that coming from. I cannot find textbox validation code anywhere. Thanks in advance.

    • Rachel says:

      Hi Mark, there is some default validation that is built into the default WPF Control Templates. For example, if a TextBox’s Text is bound to an int field, and the user enters some letters, it will cause an error since you cannot store text in an int field.

      The default validation template is usually just a red border around the control, but this template can be modified. You can also modify the validation logic by making your class implement `IDataErrorInfo`.

  6. Michel Keijzers says:

    Thanks for this clear blog … I probably am going to convert my (too big) WPF app into a MVVM app. Till now, I only separated the Model and View, so the ViewModel logic is now shared between the Model and the View.

  7. Antoine Jeanrichard says:

    Hi Rachel,
    Nice blog with good explanations!

    In most of the apps we write at my company, we have views corresponding to instances of classes of the domain model. Therefore, we wrote a framework which makes it easy to use our domain model classes as ViewModels. We do this for all our views, except the apps main views (as stated in your article about navigation with ViewModels).
    What do you think about this?
    For instance, in the example you wrote above, what would you think about putting the relay commands directly into your model, and therefore using it as datacontext of your view?

    Thanks for your ideas!

    Antoine

    • Rachel says:

      Hi Antoine,

      Glad you enjoyed the article! There are many different frameworks or variations of MVVM, however I personally like to keep my Models as plain old data objects that only contain some raw data validation and PropertyChange notifications, and to put any application or business logic such as Command handlers in ViewModels.

      I’ll still use Models sometimes as the DataContext for my Views, however I try and keep any application-related functionality out of them to keep the layers separate and make maintenance easier.

          <DataTemplate DataType={x:Type local:MyModel}">
              <local:MyView />
          </DataTemplate>
      

      Or

          <DockPanel>
              <Button Content="Save" 
                      Command="{Binding SaveCommand}" 
                      DockPanel.Dock="Bottom" />
              <Grid DataContext="{Binding SomeModel}">
                  ...
              </Grid>
          </DockPanel>
      

      Rachel

      • Hi Rachel,
        I see this article is still read a lot :-) I have a new need for insight : How do you do when your Data Objects are modified by other threads? Do you manage dispatcher calls in your ViewModels, using CheckAccess or something similar?
        Do you do it everytime, for example in your abstract ViewModel class, or do you specifically implement this for the ViewModels that will likely wrap multi-threaded-modified data models?

      • Rachel says:

        I try to never create or modify my data objects from another thread. Typically I will get data from another thread, then populate my data objects on the main thread.

        Although if I ever did need to modify a data object from a background thread, I would probably use the Dispatcher to pass the work to the main UI thread from my ViewModel.

  8. manish says:

    This looks great.. Thanks for simpligying it. Looking forward for more explanations on other UI patterns..

  9. steve says:

    Good article although too much fluff eg:
    RaisePropertyChanged(string propertyName) is never called so can be omitted and in the OnPropertChanged method there is no need to create a new handler reference, you could just use:
    if (PropertyChanged != null) {
    var e = new PropertyChangedEventArgs(propertyName);
    PropertyChanged(this, e);
    }

    But overall a very good demo of Mvvm

    • Rachel says:

      You’re right, some of this stuff is unnecessary. I never really noticed it until you pointed it out because it doesn’t really harm anything, and some of it is actually useful.

      I’ll clean it up a bit though, thanks for the feedback :)

  10. Shan says:

    Hi Rachel,

    It is a good article and easy to understanding for beginner such as me. I am building a Windows phone application. I followed your article to create the class. However, I got the erorr during deserialization. The error is “The type ‘CMSPhoneApp.ObservableObject’ cannot be deserialized in partial trust because it does not have a public parameterless constructor.” Would you have any suggestion how can I solve it?

  11. Shan says:

    I changed the ObservableObject class from “public abstract class ObservableObject to be “public class ObservableObject” then it worked.

  12. Krishna says:

    Good one. But can you please let me know who is listening to the PropertyChangedEvent and how the datacontext is refreshed while changing a property in ViewModel?

    • Rachel says:

      WPF’s binding system listens for property change notifications (so a <TextBox Text=”{Binding SomeProperty}” /> will re-evaluate SomeProperty for the Text anytime it hears a PropertyChange notification where e.PropertyName == “SomeProperty”), and you can also hook your own handlers to the PropertyChange notifications and do some custom logic yourself anytime a property changes.

  13. Rachel, thanks for a simple explanation of MVVM. The one thing that gets me thinking in circles are reusable controls and view models. For example, if we need to reuse a phone number control over and over again in different views with the same logic behind the control, do we create a view model for this?

    I can see how this would work for events, but how about the data itself that it uses? Please share your thoughts.

    • Rachel says:

      I usually have two kinds of UserControls: Very generic ones with no ViewModel at all that get passed any values they need via DependencyProperties, and more complex UserControls that are built to go with a specific ViewModel, and that ViewModel is expected to be used as the DataContext when the UserControl is used.

      I’m a bit unclear about where your PhoneNumber example would land since I’m not sure what sort of functionality you’re thinking a PhoneNumber would have.

      If you want to use a UserControl as nothing more than a generic way to display the phone number, such as having 3 TextBoxes to separate out the phone number sections, then I’d probably do the first case of building a PhoneNumberUserControl and have a DependencyProperty for PhoneNumber that is a string that can be passed to the UserControl.

      If you’re doing something more complex, such as supporting various phone number types like international numbers, extensions, etc, and adjusting the View based on the type of number it is, I’d probably build a PhoneNumberViewModel and build my UserControl with the expectation that the DataContext will be of type PhoneNumberViewModel. Then the actual application classes would have to use a PhoneNumberViewModel anywhere they want to represent a phone number, and the View would tell WPF to draw the PhoneNumberViewModel using the PhoneNumberUserControl.

      I hope I understood your question correctly and didn’t confuse you more than you already were :)

      • Yes that makes perfect sense using another View Model to represent the data rules of a user control such as a complex phone number control. I appreciate your input. Keep up the good work blogging. =)

  14. Thank you for this awesome post, This is just the thing I needed today

  15. Kasper says:

    Good work! I would just like to add that in my models, I _do_ have business logic, validation etc. The reason is that I can then use my models stand alone, e.g. in apps where there is no view. The model knows how to persist data, usually through a repository interface.

  16. mrothaus says:

    Rachel, great post. Tell me how you would handle this situation: You have another property in ProductModel, “bool OnSale”. In your view, you want to display “Yes” if OnSale=true and “No” if OnSale is false. What I’ve been doing is just making another property in the ProductModel called OnSaleDisplay which is a string with just a “get” and no “set”. This works well because I can raise a notification for OnSaleDisplay when OnSale changes (with an OnPropertyChanged(“OnSaleDisplay”) within the OnSale property.

    However, after reading your post, I suspect OnSaleDisplay doesn’t belong in ProductModel. How would you do this and who is responsible?

    • Rachel says:

      Hi mrothaus, I would actually create a converter in the View that converts the boolean value to a Yes/No value since this seems like something only the View would care about, and the converter could be re-used in other places where you want to convert a boolean to a Yes/No value

  17. Dipak says:

    Rachel , Great post. Tell me is it necessary for create Relay command class? if yes why? and there is another method without using relay command class?

    • Rachel says:

      Hi Dipak,

      The RelayCommand class uses delegates for Execute and CanExecute, so you can easily build Commands in your ViewModel without having to write a new command definition every time you want to add a Command to your ViewModel.

  18. very nice, mvvm is more clear to me now, thank u

  19. Azhar says:

    Really a nice Introduction to MVVM, I have started using MVVM after reading this :)

  20. Ghufran says:

    Hi Rachel please guide me how to Handle Drag and drop in MVVM pattern, I have to drag usercontrol

    • Rachel says:

      Hi Ghufran, DragDrop is a UI-specific operation so should probably be handled by the UI code somewhere, such as by a custom UserControl or in the Code-Behind the UI.

      If you Google “WPF Drag Drop” you’ll probably find plenty of examples, although I personally like this blog article for dragging and dropping data bound items: http://www.zagstudio.com/blog/488

      Good luck with your project!

  21. oscar says:

    Hello Rachel,
    Thanks, your example helped me understand better the MVVM !

  22. Scott says:

    Late to the MVVM game. Your work shared here is wonderful. I was in the middle of my own DataTemplate vs UserControl war. You (and one other) have convinced me, unless I have some unusual data presentation or needed extension, I should stick with DataTemplates. Love your by-line. You’ve certainly helped me understand.

  23. Scott says:

    Hello Rachel,

    Very nice description of a simple MVVM, but I’m still confused. I’m *very* new to C# and WPF, having done mostly web-based applications.

    I’m still confused as to how you are affecting changes with this pattern. I’ve gone through other tutorials describing this method and they seem to leave out the piece I’m not understanding.

    When you change the ProductId from ’0′ to ’1′ the “Get Product” button becomes active. How? When you click on the “Get Product” button the ProductModel DataTemplate appears. How does it appear? The application works as described but I’m completely stumped as to the how.

    It’s clear to me that when you change the data in the “TextBox”es an event is triggered, but just can’t see what else the delegates are doing.

    Thanks much!

    • Rachel says:

      Hi Scott,

      When you bind a DependencyProperty in WPF, you are telling the property to look somewhere else to get it’s value instead of looking for the value locally on the object. So when you bind a TextBox.Text to a ProductId, you are telling WPF that it should go look at the ProductId property of whatever the TextBox’s data layer is anytime the Text property is needed. (I have a blog post about the data layer here if you’re interested in learning more about it)

      Most bound objects implement the INotifyPropertyChanged interface, which WPF’s binding system uses to know when a bound value has changed and needs to be updated. For example, changing the ProductId from 0 to 1 will trigger a PropertyChanged notification for the ProductId property, and any bindings that rely on that value get automatically re-evaluated and updated.

      The RelayCommand I am using for the Get Product button is a special type of command that automatically re-evaluates CanExecute() anytime a property changes, so when ProductId changes, the GetProductCommand re-evalutes it’s CanExecute method, which toggles the change of the button’s Enabled properties (Buttons that are bound to a Command will automatically bind their IsEnabled to the Command.CanExecute).

      Clicking the button merely populates the CurrentProduct property, which is bound to a ContentControl’s Content property in the UI. When WPF receives notification that the CurrentProduct property has changed, it re-evaluates the binding and tries to draw the CurrentProduct object in the UI. Because I have an implicit DataTemplate defined in the Resources (A DataTemplate that has a Type, but not a Key), WPF will automatically use that DataTemplate when trying to draw an object of type Product.

      Hope that helps clarify things, and that I didn’t just confuse you more =)

      Rachel

      • Scott says:

        Wow! Thank you! It definitely cleared things up for me. I wonder though, what is determining that a button Command.Execute happens on click and not, say, on hover or on focus?

      • Rachel says:

        WPF actually evaluates Command.CanExecute when the control is first rendered, and that determines if the button is Enabled or not.

        I don’t even think CanExecute is checked when you click on a Button that is bound to a Command, unless you perform the check manually.

        The RelayCommand I used will re-evaluate CanExecute anytime a property change notification is raised, and that will alert any bindings to the command that they need to reevaluate.

        There are other commands which behave differently. One example is Microsoft Prism’s DelegateCommand, which does not automatically re-evaluate the CanExecute when any property changes (this is better on performance). To use their command, you have to re-evaluate CanExecute manually when a property you’re interested in changes

  24. I am learning WP development and wanted to try out MVVM in a sample app. This blog post helped me tremendously because of its simplicity. I extended my app to use repository pattern in model.

  25. Ronald says:

    Hi Rachel. What you say about Models and ViewModels in the beginning of your article looks to me to sharply contradict what I’ve read elsewhere. It appears that either you or they have gotten the two mixed up. What I’ve read so far has it that the ViewModel is the one that “should only contain properties and property validation” and the Model is the one that contains all the business logic–the opposite of what you explain. Have I just missed something here?

    • Rachel says:

      Hi Ronald,

      Models are typically either plain data models (think of something like a database row), or they are domain models which represents the state of something at run time. They usually only contain properties and basic validation related to that single model object itself. They are the building blocks used by the rest of the code when constructing the application.

      ViewModels are meant to be code representations of the Views. This means if the View needs a Name property, the ViewModel may contain a string property called Name, although that string property is probably stored on a Model inside the ViewModel. So although the ViewModel may contain the properties the View needs, it usually will be using a Model object to store those values. ViewModels also contain more advanced validation, such as checking if the user has access to something, or verifying that an item is unique.

      It should be noted here that some people prefer to return the actual Model object to the view in its entirety, such as I have, rather than create separate properties on the ViewModel that get/set properties on the Model. This often is faster to code and more practical, although it is not the “MVVM purist” approach. Both methods are acceptable when using MVVM.

  26. Hal says:

    Hey Rachel

    I learning MVVM toghether with WPF, as the only way to go with it. I have a question. I plan to do database connected application that use Entity Framework (base first) model.

    Please tell me whats the best way to wire up entity framework model to viewmodel?

    Should I just simply wire up entity model in constructor of ViewModel?

    Like in that example?

    //constructor of ViewModel
    public ViewModel()
    {
    db = new PackageShipmentDBEntities(); // Entity Framework generated class

    ListFromDb = new ObservableCollection(db.Packs.Where(w => w.IsSent == false));
    }

    Or this approach is not the best?

    Thanks for the answer.

  27. Jon Wells says:

    Really useful read, thanks. I’ve not been working with WPF/MVVM for long and this helped cement some of the fundamentals

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 96 other followers

%d bloggers like this: