MVVM 101 - Model-View-ViewModel Architecture for Xamarin.Forms & .NET MAUI (also WPF, UWP, & More)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
today we are going to deep dive into mvvm model view view model with data binding and commanding for xamarin forms so tune in all right welcome back everyone to another xamarin 101. i'm really excited because today is one of my favorite topics it is all about architecture specifically around mvvm this is one of the core fundamental building blocks of building applications with xamarin forms because it really enables you to sort of really separate your code and with data binding it enables you to really write less code and be way more productive when you're building user interfaces and the cool part about mvvm and data binding is like i said it enables you to separate that code but there's a lot of magic that enables you to automatically have the user interface update for you when you change values and additionally vice versa when you change values in the ui it updates over in the code behind too so i normally don't do this but we're actually going to go through a few slides because i think that that really you know exemplifies how mvn mvvm needs to be sort of taught in a way and then we're going to write some code then we're going to talk about commanding which is part of mvvm and data binding and then we're going to finish it up so let's head over here all right so nvbm data binding they're actually two separate things mvvm is just an architectural pattern and data binding is like the good awesome stuff that makes all that magical user interface update in real time so when we talk about mvvm i like to put it in sort of a few boxes here where the view that is our user interface that's that xaml that we've been creating so far and it's how to display information because we put a label we put a button it's how we're displaying our ui and our and our information now our view model you can sort of think of this as the code behind of your view but it's most likely going to be abstracted into a separate file which can be easily unit testable so here's how the flow goes the view can send data over to the view model and vice versa but the view will always send events so data let's say you enter something into a text box it will then update the view model the actual property or if you update the view model property it will update the ui events is like if the user interacts with the ui it can then notify the view model that hey something is happening and then you have this model over here and that's just really our business logic our data objects this may be interactions with a web service with a database or it just might be a person class or a monkey class or something like that it's the just data and the idea here is that is separated from your view so you can change the abstraction maybe today you're hitting an azure backend or a sql back end but you need to change it out for azure function back end you might you know put that separate logic so that way your view and your view model don't really care they're just really of here's how i display it here's the data and here's the actual data objects how i'm gathering them so it's sort of this nice separation here now the cool part about mvvm is this magical bit that lives between the view and the view model and that is data binding and it's built directly into xamarin forms you know to do anything it's all built in all the data binding magic gobbly awesomeness is all in there so the core of data binding is something we call inotify property changed and this is an interface that xamarin forms is listening to to be notified when you change something in your code behind now there's a bunch of different libraries like mvvm helpers the xamarin community toolkit and actually a xamarin forms page already implement i notify property change but this is sort of the core here of what it would look like and we'll go through this and we'll write the code as well and then next week we'll take a look at mvpm helpers but this is sort of the core is i notify property changed has an event handler that xamarin forms is subscribing to and it's all based on the name of the property so what this means in practice is if i had a person class of first name last name for example first name here i would i would for example have a normal return of let me get my first name and then the set whenever i set it i will say on property changed equals first name and we'll do this when we take our current application which is counting up and we'll automatically do this and we'll see that in the ui which is cool so there's a few ways to do this if we're doing code behind in c sharp you can actually say set binding and we'll say the property name and then whatever the property is so first name first name most of us will do this in our xaml code behind if you're doing xaml that's what we'll be doing here today and this is a really cool binding syntax where you just say binding first name boom you're good to go so that's really really easy another thing that you can do is you can have different modes and xamarin forms is really smart about picking the default mode for it like a label it's only ever going to be one way which is from your code behind to the user interface where an entry that you type in will be two-way which means that the ui can update the code behind and the code behind can update the ui which is very very nice so just be aware that there's a few different modes and i'll put links to the documentation below too so let's go ahead and do it over here alright so here we are inside of our application this is what we saw before um if you watched the previous episode i'll put a link over in one of those corners and then below it's in the xamarin 101 playlist here but it's a simple application that says you clicked this many times okay so every time i click it it updates the count now how this works is that i have a user interface that is very simple it has a label and has a button so button clicked and then here i have a label that is says click me here i've named these with label count and button click if i go into the code behind over here let me go ahead and open this up over here here we go i think i'm in this page there we go we can see that i have an int count equals zero and then i have a click event that says button click underscore clicked and when that click event happens i manually update the label every single time i have to get reference that label update the code behind and go from there so it's quite a lot of code that i would be putting in there so let's modify this here what i'm going to do is i'm going to keep this count but i'm going to create a public count here i'm going to say string so i'm going to display a string i could also do string formatting inside of my user interface but we're just kind of a string for right now and i'm just going to say count display we'll just call it that and here what we'll do is we will go ahead and say we're going to need a code behind of string sorry count display and here we're going to say click me there we go that'll be our default that we have in there and then we'll do a get and the get here will just return the current count display and then on the set there's a few things here we're in the code behind of the xamarin forms page and if we actually right click and say go to definition we'll see that this is a templated page if i go deeper this is a page if i go deeper this is a visual element if i go deeper one more time and i go to definition we'll see that this is actually a navigable element there's all these interfaces that it implements and if i go deeper into it we'll see that this is an element and if i go deeper we'll see that there's a bindable object this is built into xamarin forms if we go into that one look at all this hierarchy we'll see that there is i notify property change it's built in it's right there which is nice so what i'll do here is i'm gonna say if the current value that you're setting it to equals the count display then let's just return because it's the same value you don't need to do anything else if they're different we'll say count display equals value and then what i'll do here is i'll say on property changed which is built in let me zoom in here really quick and what we'll see is that it's on property changed string property name now this property name is the name that xamarin forms is going to look for and update in the ui so that is count display so there's a few ways of doing this first and foremost i can put in count display i can just put the string in there i can also come in and i could say name of okay and that's really nice because that's a nice c sharp feature that enables me to right click rename and it would rename this for me and this just will just display the string but traditionally with on property changed events there is some automagical things that are built in so if i actually click i should click down into this one more time go to definition go to definition go to definition let's go to definition and one more time go to definition and keep going and going here we're going to actually see that down in this on property changed right here that this is a caller member name property and what's cool about that is that this is a part of the um automatic compiler settings so i think it's actually inside of these using statements up here yeah the system runtime compiler services and what that does is it will automatically if you're in a property a member name it will automatically set it so if you're inside of a set of a property you don't even have to put anything in here like that you can just leave it blank and it will handle it for you automatically it'll assign it the reason you may want to pass in something is let's say we had another property which was like you know multiplication display we could also raise that event too and then we could increase that so here's what we're going to do is now we have this instead of setting this label here what we're going to do is we're going to say count display equals this okay now there's you know a little bit of magic here going on because i'm just setting this property it's going to call this and it's going to go ahead and then raise this property changed now the only thing i need to do is i need to set the binding context here the binding context since i am setting it to this page is going to be this and what this will do is tell xamarin forms to say hey listen to myself subscribe to events on this object and whenever on property change occurs automatically update it for me okay so let's go back into our ui and now what's cool here is that we actually don't have to create the backing field at all i actually don't have to manually set the text property we can now just say binding to count display that's it okay so binding count display and now i'm going to run this again and what we'll see is that the exact same application will work as expected we'll get the click events here and then in our ui it's going to automatically update for us so let's let it load up here and now when i click you've clicked this many times which is pretty awesome so i'm not accessing the variable i'm not creating the backing fields like my ui doesn't know about this so if i create another label right here's what's really cool if i put let's say i put in another label and i put this i guess underneath let's put this in oh i guess on top if i do text and i do binding to count display right and i hit save there what we'll see oops up top here is that you clicked 28 times see that so that's really really neat because it enables me as a developer to not hard code and you know i'm going to say bind because it's the wrong word for it but basically you know restrict my ui and my ui elements to be bound together this dearly decouples my business logic here so that really enables me to to be very very productive here in creating this type of code inside of my application which i think is is really really neat now the other thing i could do at the same time is if i was going to get really crazy if we maybe set this to entry instead of instead of this here now we have this big entry here so notice here that as i remove this it's the same data binding and i say hello world look how it updates below so the entry is setting the property automatically here via this data binding and then it is updating the label because it's subscribed to events now notice here that if i say click me again both of them update at same time and that's really really cool you don't have to worry about what the object is what the data type is you can have this really cool powerful data binding built right into your application so that's really really neat all right now the other part that you may have noticed is that i had to click that button and i had an event now so here our button is directly bound to our user interface via that click event and this is exactly what we see inside of a lot of our applications is we have a click a button or an item selected or item changed or text entry changed and whenever your user taps on something it raises an event so this means that that logic inside that click handler isn't very testable at all it can't it's not really decoupled in any way because it is an event handler it's actually raised the event you'd have to click it so and additionally then it has to be handled in this code behind file right you have to have these senders these event arcs you have to have all this data in the code behind and then there's this reference to this event that is kept there so part of data binding that's really cool is something called commands and there's an interface for this similar to i notify property changed but it's an i command so an i command enables us to do a bunch of things you can pretty much for all intents and purposes just execute the event and you can additionally pass a parameter into it which is really nice we'll get into that maybe in some future episodes there's also some additional properties such as can execute and an event handler that you can you know change your property so you can implement a function that says can this method this command be executed and xamarin forms will listen and respect that and automatically disable events based on that so for example you can have can execute true or false and when it's false it will automatically disable that button which is really really nice so this command is just an interface and luckily this interface is very very simple and additionally um it's already built in with xamarin forms so again can execute this is going to be called to determine whether it's enabled or disabled execute this is actually executing the method and then can execute is something that we can call manually and raise an event when we're going to change that so the can execute can be recalled so like i said xamarin forms has this built in into a bunch of different user interface controls such as menus buttons toolbar items text cells and a bunch other and it looks a little bit like this it has the same exact properties if you will and syntax as the data binding that we saw earlier the command property on a button for example binds to an i command so where i was binding count display which is a string i could bind a increase count command to an i command and to implement this thing what's really cool is that you can also pass in additional parameters so for example here i could pass in a string to a tap gesture recognizer that you could add to anything that would pass it down from your ui down into your page now like i said earlier luckily command and command of t which is the parameterization of it are automatically built in to xamarin forms so here for example we see i have a give bonus command and this command i just create a brand new one and i have a boolean that says can give bonus and then one that says on give bonus so let's go ahead and do this really quick here so what we're going to do is get rid of this nasty clicked handler here so i'm going to go into the code behind once more and we're going to create a new public i command and this is going to be called increase count and i'll just say get so here it's going to ask me to import my system windows input this is a standard system interface and then what i'm going to do is come up here and i'm going to say increase count equals new command and that's built in two xamarin forms so here's this command and command of t i'm gonna say on increase okay actually i just need to pass that there now what on command takes is a few different things actually so it takes an action which would just be a method that's a void it can take an action with an object it can take an action and a function that returns a boolean or both a parametrized object and parameterized functions if you're passing strings around you could do that too inside there so let's hop out here so what i'm going to do is instead of creating this button clicked event i'm going to say void on increase here there we go and see how it goes away so it's just a method that's going to take in and we're just going to go ahead and take these two and put it right here there we go perfect so now a bunch of our code is really decoupled here because now i can go back into my ui over here instead of saying clicked i can say command and i'll say binding to on increase oh sorry increase what did i call it uh increase count there we go per right and then i can get rid of this name so i don't need to access it from the code behind anymore all right so that enables me to say hey command increase this count and optionally i could pass in things i could pass in a number in there to say you know increase it by two increase it by four increase it by five as many as you want you can continuously do that okay so here we go our application is loading up one more time over here and let's get rid of this entry we don't really need that there we go and now when i click it notice that it automatically calls this code behind for me i'm going to click it it automatically clicks it for me my count is the same my string is here and it is good to go so here comes the power of it right now we just got started everything is inside of this file let's go ahead and add a new view model i'm going to say new item and this is called our coffee equipment page so i'm going to call this our coffee equipment view model i like to sort of name my view models the same as my page i have a coffee equipment page coffee equipment view model we're going to make this public and here what we can do is we're going to say bindable object because that is built into xamarin forms right you can just be one it's just built right in now there are other things like prism and mvvm light and xamarin community toolkit and mvvm helpers that have their own bindable objects with nice things and we'll look at those in the future but it's built in look at all that documentation it's all right there so now what i can do is i can take all of this code check this out boop i can pull it into my view model and here we'll just simply pull out this initializer i'm going to say public coffee equipment view model set that method there bring in this i command there we go awesome now we're sort of getting there we're good to go now i could do a few things here this is this is interesting i could for instance say new coffee equipment view model same exact thing over here so i could then bring in this namespace and that will work okay that will totally work just fine the other thing i could do is come over into my view here and i could say content page dot binding context i'm going to say local view models and um i'm going to say local let me do view model sorry view models live coding paste that in visual studio will bring in our name space for us there we go and now we've set our binding context in our code so whenever the page is created it will automatically set this so everything will be a new instance every time so you have to decide if that's what you want but one of the nice things with that is check this out if i zoom in here let me zoom in one more time is that now when i set a binding on this label for example i get count display right here inside of it so it gets everything that's part of it so here's my count display boom just get that right built in which is really cool by setting the binding context that's here now additionally one other thing that we can do is i can say x colon data type and i can say view models coffee view models this line of code right here okay the data type this is called compiled bindings and what this does it will increase my performance of data binding and additionally will give me checks when i compile my code so if i was to for example miss type display count here check this out binding discount display was not found right so a bunch of things i just did there okay the first thing is i set the binding context that gives me intellisense so ideally i won't type that wrong because it'll be inside of here then i set x colon data type which is a standard syntax here that gives me compiled bindings again i'll put this all in the show notes for you to take a look at that's going to improve my performance and also give me compile time checks okay cool so now check this out our code behind it's empty it's blank it's good to go there's nothing here this view model could be in a completely separate file completely separate it already isn't a file but it's completely a separate assembly for example a different project and would work just fine so check this out now click me it works exactly the same now our code is completely decoupled from our user interface 100 and we are completely good to go now we can take that view model completely test it to make sure that when i call that method it actually increases our account now for my user interface that again is completely decoupled there's no x colon names there's no click handler events there's no manually setting properties everything is there magically for us that is mvvm in a nutshell that is our data binding that is our commanding that is our architecture in our application all right that is just really an mvpm101 there's quite a lot more that we can tap into for mvvm but even just knowing this this alone will get you i would say 95 percent the way there i'll of course link to documentation from xamarin forms for data binding and xaml and mvvm goodness in there but i really hope that you found this video really insightful gets you off the ground running doing mvvm and being super productive because once you do this once you're just gonna start knocking out all this code all your data bindings all that stuff now don't forget that every single week i'm putting out brand new episodes right here on my youtube channel so don't forget to subscribe and ding that notification bell not only am i putting out brand new stuff on xamarin but i'm also putting up my live streams that i'm doing every single week on twitch on fridays at twitch.tv slash james montemagno the latest series is me recreating the user interface of the peloton fitness application so tune in to a few of those i'll also put those up in the corner over here but also make sure you subscribe ding that bell one more time just to really make sure you're in there so you get notified every time i have a brand new episode anyways i so i hope that you super enjoyed this episode if you have any questions put them down in the comments below give it a thumbs up and i'll know that you want me to make more of this type of content so until next time i'm james montemagno thanks for watching and have a good one
Info
Channel: James Montemagno
Views: 26,948
Rating: 4.976048 out of 5
Keywords: xamarin, xamarin.forms, mvvm, model-view-viewmodel, xamarin 101, uwp, wpf, xaml, testing, visual studio 2019, visual studio, ios, android
Id: Pso1MeX_HvI
Channel Id: undefined
Length: 27min 3sec (1623 seconds)
Published: Thu Jan 07 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.