Intro to Model-View-ViewModel (MVVM) Pattern for WPF in C#

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome and thank you for joining me for this presentation my name is David Anderson and I'm an independent software developer for decom productions and today I'm here to demonstrate using the mvvm which stands for model view viewmodel architectural pattern with WPF and it is specific to WPF it doesn't work well with technologies like Windows forms because the data binding and those technologies are far limited compared to the two-way data binding that WPF provides so I'm not going to talk a lot about specifics about all all the things you can do with mvvm instead I'm going to focus on the overall architectural pattern and what you should do and throughout the demo I'm just going to show you how to do things the right way and guide you in that direction rather than talk about rather than demonstrating the current ways of tight coupling and everything we're just going to flat-out go straight in it W or excuse me mvvm before we actually dive into the demo however let's actually debunk what these three terms mean neither none of these terminologies or anything new model is just a synonym for entity it's a customer it's an order it's a product it's basically just your data object you know if you're using any framework all the objects that are generated by entity framework for example in database first or pocos all those are your models so this is nothing new the view is just a synonym for user interface it can be something like a user control a window even a button so that's all that means and view model is just a program logic a business logic the actual guts that does all the work the important thing though is to understand the relationship between these three things the ID the idea behind mvvm is that your view will never talk to anything it will be completely decoupled so your view should know nothing about the view model and vice versa your view model should know nothing about the view and the way will communicate between the two is through data binding in WPF and because their data binding is so powerful we're not having actually hard code anything we could do it purely in example now the relationship between the view model and the model is completely the opposite it's okay to have a strong relationship between the two directly communicate but you still want to have the guts of your logic in the view model and your models should generally be lightweight have your business logic business validation rules would be a more proper way to put it and then the view model should actually be the guts of I'm going to I'm going to load the data save the data manipulate the data take user input all that good stuff and the idea behind these relationships in mvvm is that you can swap out your views without any pain designers can work with your code without having to well they can work with the views without having to touch code and it's just a really great pattern and once you get the hang of it you'll find that it's actually very easy to make changes to your software so let's go ahead and jump right in the first thing we're going to do in our project here it's just the WPF application we're going to create our three folders called models view models and views and again try not to get the terms mixed up just think of them your model is an entity just think of your view model as your program logic and views as Windows and controls the first thing we're going to create a customer model so we're just going to call this customer and we're going to keep this demo as simple as we can and we want to implement the I notified property changed interface because this is at the core of how WPF does its data binding it subscribes to events like property changed to update its user interface and things like that we're going to create a default constructor for our customer and we're going to take a string parameter call it customer name and we'll have a property called name that will create here in a moment remember that to implement inotify property change do that via a code snippet so there's nothing new about this model it's basically just a plain old CLR object very lightweight has a single name property there's nothing special or mvvm specific about it so we're done with that let's close that out let's create our view model now the point of a view model is to perform some action so you want to separate logical parts of your application maybe you want to edit the profile of customers so you want to be able to edit their first name their last name email things like that and then you might want to have another component that displays read-only information you may want to have another component that does something else with the customer so there's different ways to group your application together in this case for the demo we're just going to create a view that allows us to edit the name of the customer so for this we're just going to call this customer view model and because we need to manipulate a customer we need an instance of one so we're going to create a property for that and we would maybe populate this by loading it from a database maybe an XML file wherever you're storing your customers since we're doing a very simple demo and we want to keep it lean and to the point we're just going to do this on the constructor so we're going to set the value of our customer to a new customer and I'll pass in my first name to the constructor and then some of the other functions of the view model is while if we're if we want to update the properties of the customer we want to be able to save those we want to create a function called Save Changes and because we're doing this in theory I'm just going to use a debug assertion to display dialogue okay so we have our basic logic we have the ability to access the customer properties we can update the customers name any other properties we want to add in the future and then we can call the Save Changes method to persist the changes to our data source again in theory so now we actually need the user interface to be able to do all this we're going to create a window and call this main window okay so we have just a very simple form with a label text box and a button now we need a way to get the data from our view model into the view and we're going to do that through data binding and it's primarily done through the data context property the window and this is really one of the only times you want to write anything within the code behind other view and this is okay and you also need to remember that mvvm is not a solve everything pattern either there are times when mvvm is not the right thing for the job and you need to be aware of when those things happen it's okay to break the pattern most of the time you probably won't need to do that but for the example of like setting a data context this is okay so we're going to set this to a new instance of our customer view model and that's it aside from that we should never have to write any code in the view now what we can do is for our text box we can set text property to binding on the data context as our data source and we could set it to customer name and if we run this we should get a value of David oops and when do hips accidentally created the window and the route update the namespace there we go so we should get a value of David oops I did it again we need to move that to our views form so we should get a value David in the text box so we're able to retrieve the value from our view model and we did that without hard coding anything so let's go ahead and close that and now we need a way to actually update the data now normally you could use the click event for a button but that would create coupling not only would we have code in the code behind our window but we would also have to write code to access the view model which couples the window to the view model so instead we're going to use window scuse me WPF s command system so you can say command equals binding and we're actually going to specify an update command on our view model so we're going to bind again to the data context which is set to an instance of our view model and we are going to bind to a property called update command and in our view model we are going to create a property called public I command and we'll create our command here in a second this will be called update command and in our constructor we're going to say update command equals new customer update command and what we're actually going to do is create a command that implements the I command interface called customer update command so we're going to add a new folder in our project called commands we'll add a new class now the immediate things we need is to derive from I command and we also need access to our view model so in the constructor of the command we're going to say customer review model and let's go ahead and implement the I command interface and there's three main pieces to this there's the can execute changed event now because we're implementing the interface directly and we're not deriving from some already concrete type like routed command or anything like that we need to wire this back up to the WPF command system so we're going to do add command manager require ISA jested and we're just going to pass off our events to the command manager so now we're wired back into the WPF command system and the can execute method this is actually used for controls for example our button will enable or disable itself based on the return value of this method so what we're actually going to instead of putting business logic in the customer update command class we're going to pass this off to our view model so we're going to say return view model can update and we're going to create a property stub in our view model and then for execute we're just simply going to call view model dot Save Changes so now we're done with our command class let's go back to our view model and grab our property stub and now we can import our commands namespace and pass in an instance of our view model which is just done using this keyword alright so now we can go to our main window and let's go ahead and run the program and you can see here that our Update button is disabled and that's because we didn't actually add any logic to our can update property and the default of a property or field for boolean value is false so let's go back to our view model and we'll make this read-only and we'll say return not string it's null or whitespace and we'll say customer dot name and then we'll say if customer is null return false so if our customer is null are not set we're going to say we can't update something that doesn't exist and then if the user excuse me the name of the customer is empty or null we're also going to say we can't update so if we run this now now that we have some validation logic in there you can see that our update button is in fact enabled and as I update the value of the textbox and click the Update button you can see that now that the text box is empty the Update button is disabled and it did not execute now real is realistically we want the Update button to enable or disable as we're typing text because the way the default binding behavior is that the underlying data source does not update until focus is lost from the text box so that's why the update button didn't disabled until I clicked it so we can change that by going to the zamel and we can go to our textbox binding and say a update source trigger equals property changed instead of lost focus and we can run this and if I erase the text you can see that disabled as soon as it detected there was no characters and if as soon as I type a character you can see that it's enabled again so I can set the name to david anderson and i can click update and what that does is it calls the update command can execute method that we implemented in our command class and you can see that our debug dialog was displayed and all our can execute method did was call through to our view model to the Save Changes method and you can see that it's displaying the new value in our debug assertion now if we go back and we're actually done if we go back and look at all this auras Amal is very clean very simple and in the code-behind of our window we never touched it other than setting the data context and there are ways to remove that you don't have to set the data context and the constructor you can instantiate your window yourself and set the data context that way so you're not actually accessing any of the code of the window so you don't have to do it this way but this is acceptable for mvvm the whole point is that for everything else you're not writing code in your code behind go back to our view model still pretty simple but this is where all it's okay to have a very heavy view model so throw all your logic in there properties methods events and then for your models they should generally be lightweight so you can already see that the power of this pattern is we can go into our window now let's close everything else and I can modify the user interface I can say you know I can move stuff around and I don't have to touch any code to change our user interface now I could even change the type of controls that these are and it won't break the code so I can change see textbox we could change that to an editable combo box if we wanted to I prefer to run that we can see that we can change the text at the combo box and we didn't have to change a single line of actual code to do to change the user interface and that is the power of the MVVM pattern now obviously that mvvm can get complex especially if you're dealing with large systems so I will be making more instructional videos come in the future look forward to those but for now I wanted to get the basics of it out there and if you have any questions as always post comments post on my blog email me on everything is great so thank you for joining me for this presentation and happy coding
Info
Channel: DCOM Engineering, LLC
Views: 326,804
Rating: 4.8380785 out of 5
Keywords: c#, .net, wpf, mvvm, design patterns, design pattern, pattern, mvvm pattern, model-view-viewmodel, xamarin forms, model view viewmodel, interview questions, windows presentation foundation, how to, android viewmodel tutorial, c# viewmodel tutorial, wpf viewmodel tutorial, mvvm viewmodel tutorial, wpf mvvm viewmodel tutorial, software engineer (profession), android viewmodel, viewmodel, c# viewmodel, wpf viewmodel, c# mvvm viewmodel, mvvm model tutorial, control, content, unit testing
Id: EpGvqVtSYjs
Channel Id: undefined
Length: 23min 6sec (1386 seconds)
Published: Thu Jul 05 2012
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.