Episode 5: MVVM & Data Binding with Xamarin.Forms

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome back everyone to another episode of the xamarin show we're here in the channel 9 recording booth it's awesome it's beautiful I'm your host James Monta magno and today we're gonna be taking a look at mvvm or model view viewmodel the base of any xamarin forms application and even xamarin application if you're using some beautiful frameworks such as mvvm cross bind or mvvm light I'm a huge fan of mvvm it's a great way of architecting code to abstract away your business logic from your user interface every single application I've created probably in the last 10 years has been around mvvm now I'm gonna talk a little bit about the architecture and why it's important to know how mvvm works but we're going to focus on the data binding part and the data binding framework that's built into the box of xamarin forms so it's gonna be kind of a 101 introduction but if you're new this is gonna be great if you've been do as Ameren forms for a while maybe you'll pick up some tips and tricks so what is mvvm I talked a little bit about that it's a model view viewmodel approach we may be familiar with MVC Model View controller specifically if you've been doing any web development or asp.net development for instance if your model talks to the view that can talk to a controller and this kind of since cylindrical round and mvvm is very similar there's throw in some more V's and some more M's got rid of a/c and what you can think of it if I go ahead and show you a diagram here we'll jump into the slides is that think of it like this you have your view it's essentially how you display your information this could be anything it could be xamarin forms it could be an Android XML file it could be a storyboard file it's just how you display your information then you have your view model and we can see how the data and events are flowing here your view model is a representation of what you want to be displayed and it handles how data is flowing to and from your view additional when a view has some event such as a click of a button it'll pass that up to the view model and the view model will interact and pass some data back and what that view model is doing is it's interacting with your model your business logic your data objects maybe your as your store your sequel a database anywhere your data is a living so this way your view is not talking directly to your data it's talking through a view model your view is going to be platform-specific or xamarin forms that can live in the same and Sam reforms the same library or a different library then over here your view model and model are completely portable the idea is that you could completely swap out your user interface if you wanted to and use the same view model and model in the code-behind now mvvm is just an architecture pattern it's not data binding now what is data by Nansen that's a good question because what is data binding is what an mvvm framework brings into the mix the idea here is that I have some code that's in my view model and I want it to magically show up in my view and that's where this kind of magical data binding framework lives it's that glue that binds your view to your view models specifically and that's where xamarin forms data binding framework comes in so think of it like this before we jump to the source code is you have some object this your view model has a property on it maybe first name there's this magic data binding layer that has some syntax in the view and it knows how to talk to and from the user interface control source to target target to source your source is your in your view model and your target is your user interface so let's take a look at a xamarin forms application all I've done here is I went to file new project and I create a blank sam'l application you can create a blank application whatever you want it's just using a portable class library now all of my code for this application is gonna live over here inside of my portable class library I have models such as a contact I have an ad contact view model and have a main page so these two pages are going to relate in Saida here let's look at that data that add contact view model what I wanted to do is have a very easy way of simply adding some contacts to a list so maybe this is that that page of the application I have a few things inside here such as name website the best friend is a busy and then I have a display message that says your new friend is name this and if they're if they're your best friend or not what their website is and is busy flag with some getters and setters and then I have a few methods such as launch website and save contact now this is just for demo purposes you probably wouldn't put a four second delay but maybe this is calling off into my model and saving that into my Azure store or my sequel store anywhere else that it may be doing and then I just pop up a display a dialog here but the point is that I'm actually calling this is busy so what is the core of data binding well let's say that I set these name properties to something else so let's say I set this to James Monty magno there and I set website to my blog Mott's codes there we go now I've just set the default properties and I need some user interface to display this stuff and that's where this main page comes in what we can see here is that I have a stack layout with some entries and another stack layout with a switch in it and we can have a place holder here says your website now if I run this we can see that I have a label of name and entry essentially enabling me to type into a box and then I have a website and I have a best friend what I could also do down here is add another label and we'll put some text here and we want this label to be that display this display name inside of here so first off how do I get my view model to talk to my view well if I want to I could type inside this entry box well if I just run this first let me just go and run this we can see looks like over here on my Android emulator right now it's not gonna do anything it's just gonna be a representation of my view that I have and we'll see the switch will see the label but nothing is dated abound it's essentially an empty blank view with absolutely nothing on it and in fact if I go to the code behind here of the main page we'll see that there's literally nothing inside of it but we'll need to actually update that when we actually want to run it so here it is and we can see name full name website best friend these buttons that do nothing so how do we date a binding get some stuff in here that's a great question so what we want to do is come up and use a very specific binding syntax I'm gonna make this even bigger to focus on it the binding syntax enables me to say what is the property in the code behind and what do I want it to bind to here so it'll be binding and this will be named if we go ahead and put this side-by-side this would be nice we can actually go ahead as I set this work well does all of them that have been nice all right so we have named best friend and website so these are the names of the properties their public strings and that's very important here I can do another binding to website down here for switch well these are strings and those are strings and here we have a toggled property which is actually a boolean or I could say sorry is toggled that's a boolean which combined to a boolean so I'll say binding to best friend there we go and then down here we have another label and this label is display message it only has a get so say binding to display message there we go so I've had my bindings in place this is a simple data binding syntax so automatically the entry will know it's a bind and show that name the same thing here for a website it'll go ahead and bind to that website property now if I run this application one more I'm will actually see that nothing will change so it'll close it down and it a relaunch it because I have these binding syntax in places so you think oh I should automatically display why would why would this not display in the user interface so let's take a look here go ahead and relaunch is it and we can see it should have at least picked up my name and stuff like that from the coab online if i type anything it's nothing's being displayed for that display message so how do i actually bind it together so I can come into my page code behind in every page every control in xamarin forms has something called a binding context the binding context is what tells am reforms this is where you need to look so this binding context I will create a new ad contact view model and bring in my namespace setting that will set the binding context of the entire content page it will then trickle down to all of the children inside of it if I wanted to set my stack layout to have a different binding context it would trickle down to the children of that stack layout so check this out I'm gonna go ahead and actually put it in a debug mode so we can see what's going on here we can go ahead and open up our solution explorer and go back into our add contact we can actually add a breakpoint here into all of these on these getters boom we actually hit a breakpoint xamarin forms is now looking saying the data binding context is in place and here it is James monta magno it will now do bestfriend it's gonna go down that tree again bind it up there we go now we're displaying this here and we can see best friend your new your new friend is named James Monta magno and he's not your best friend so maybe for instance we would want to set it so if I had a break here on the set we can actually see that down here it has a two-way data binding system so even though I have added nothing else into my application any object that you can interact with has a two-way data binding system so one-way means that it'll update from my view model up but if I want to send it back down I will actually then send it down back into my code behind so now I can continue and there we go it's now updated automatically for me which is super cool but one thing that we're noticing is that your new friend is named James and is not your best friend hasn't updated because he is now my best friend how do I actually now update this here automatically well let's take a look now what I want to do in this instance is have a way that to notify xamarin forms when something is updated so xamarin forms can tell my view model when it's updated the user interface but how do I tell Sam reforms that I have updated something how we do that is implementing an inner freight interface called I notify property changed this lives inside of system component model and then when I go ahead and implement this interface here it is it is a single event of property changed event handler this is an event that I personally can raise and xamarin forms through the binding context will automatically subscribe to property change notifications so I could come in and I can create a something that I can call called on property changed and this will take in a name which is going to be the property name and what I can do is I can say property changed and I'll make sure it's not null so we'll use the null coalescing here null checked operator to make sure it's not null and then I will invoke and I'm going to say I'm the sender and I need to give it some new property changed event of the name there we go so as long as it's not in all someone subscribed it to be good now what this lets me do is that any of my actual properties back here I can say hey you updated that you updated this best friends I can say on property changed I think it's a best friend there I'll go ahead and drop these down a little bit I can specify the string and now notice that this string is here the same as that additionally I could just say name of which is the C sharp six that will that will be the same that's probably what I want to do in case I rename it so now I could come in and say you know what I've changed my best friend and also since I've changed that update your displaymessage there we go same thing down here for name whenever I update the name let me go ahead and pass in the name property this will tells a more informs that hey you've updated the name property and the displaymessage and make sure that you go update these and it'll go ahead and reevaluate everything same thing we'll do down here for the website there we go perfect website and additionally let's go ahead and do it for the isbusy which we'll use in a second so we'll say is busy now you may be saying well James these name up so it seemed very tedious we don't need these and most of the time you're only gonna update one property so for instance here when I actually say save contact I set that to is true and that's why I want to raise this property change in the center cuz I set it in the code-behind I need to tell xamarin forms that so it's really great if I'm changing a property in the code-behind or I'm updating some other property but these seem pretty tedious so what we can do is we can actually add an attribute here called caller member name and this actually lives inside of a system runtime and we'll say give it a default of string not empty so the caller member name what this attribute does is it will automatically call this method with the name of the property that was passed so I no longer need to pass in best friend here it'll automatically take the name when they come down here for name it'll be the same thing and I still want to update the displaymessage here and I still want update I don't need to update the website so it's really nice I can just say get rid of those and just call on property changed so now let's go ahead and run this application again and now what we're expecting for it to see and do is update the text whenever I actually change this let's go ahead and do this here and here we go we'll go ahead and redeploy this data binding of course I'm just showing you here on Android and Zarin funds but it'll work on any application so it's just one place so here we go and I can say James Monta magno and as I type as I type I'll zoom in here watch as I say Seth right I say James or a gal de Icaza inside of here you know you can change the website you can change here to toggle this on notice that is my best friend is not my best friend comes in to here automatically really simple and it's near instantaneous because as I'm typing we can see here if I go ahead and put a breakpoint let me zoom out I can put a breakpoint right here so whenever I call and I update this name as I type it oh not debugging let's go and debug it as I'm typing it'll actually update the name property tells amber informs that hey I'm updated and xamarin forms will re-evaluate make sure things have changed and then it'll update this display message so let's go ahead and continue on here and so reevaluate a few things here we go maybe I'll change it here on property changed and notice here on property changed is right here of the display message I'm gonna go ahead and toggle it and it automatically now is reevaluating the display message been now a knows to go ahead and update it right here toggle the best friend same exact thing aria you eight may be saying well what if I don't want it to change and call the code behind maybe I just want it to only be one-way data-binding but so for instance what you can do inside of here is that these all have modes so I can put a comma after the name and say mode and then I can say equals one way there's one way to way or one way from source so there's three different ways so if you just want one shot and say just listen only update it ever once I can just say one way or one time one way will only update it from the code-behind up and two way it will go back and forth so it's an easy way of updating these properties like I said you usually don't have to mess around with the mode that are inside of here but if you have some elements data binding to each other you can actually adjust the mode when you want things to update inside of it so for instance if you don't want the let's say pull the refresh and xamarin forms in the ListView to update your is busy then you would turn that off cool so let's take a look here we have this open website and this contact so what I could do here is I could say I can do something here such as an activity indicator I'm gonna say is running and what's up this too binding of is busy there we go so let's take a look at how this actually works so I just want to adjust this is busy because it's gonna be false by default so you'd come in here and I could say you know what if if the name equals Miguel well set is busy to true else well set is busy to false pretty simple so let's go ahead and rerun that again and I'll once yudish what I want to show you is that in this instance I was typing a name and it was updating the display message so I was telling xamarin Forms to update this what we want to do is we want this in the code behind to update the user interface for this is busy so now when I come in and I type in Miguel it'll automatically trigger is busy which of then is triggering this to change so that's how we get that data binding to work when I stop typing it it automatically updates this is really nifty when you want to do something such as make a network call and you're gonna users are gonna be waiting cool so let's talk about one final thing of these buttons how do I get these buttons to actually click there's a few ways of doing this I could come in and I could say X colon name and I could say button website and what I've done is created a backing field for this button I could come inside of here and now say button dot click plus equals and I could implement a click Handler and then I could do they are I'm gonna go ahead and save this view model out view model and then we'll new it up here and then I can say view model dot and maybe I want to open the website or something like that but I can because I've made these this launched website a private function the idea is that I don't want my user interface interacting with my code behind so what I need to do is have some way that I don't need to do all these click handlers and how we do that is with something called eventing so we go and delete all this cooks we don't want this extra code in my code behind you show you what this looks like at a high level say a deer is that you have a click that click Handler there's this magic binding layer and xamarin forms that'll take this action it'll handle the event for me it'll pass a command that is bound to an actual event in my code bind it'll access some data do some stuff notify a change to the user interface such as R is busy flag get some data and then update our user interface and I'll say hello or it'll do something so it's kind of our flow of our data and event commanding and this is what we want to focus on right here one two three the command so let's go back to our contacts here in our code behind we're going to create two public commands and a command is something that's built into xamarin forms which is it is an implementation of I command and an I command if we go and peek into that has a event handler to execute data change as a can execute here for instance now and it has all these built-in event so I can say launch website command let's do it get and then we'll go ahead and do a save contact command and this is what we can data bind to right here so I can come in I can get rid of this whole thing and I'll come in and I'll say command I'll do a binding to launch website command it's just a property in my code behind and now we'll have another one here that is set to save contact command there we go and that's what's gonna be right there now we need to tell xamarin forms what to do here so we need to new these up so I'm gonna go into my constructor and I'm gonna say launch website command and set it equal to a new command and this command takes in an action so I'm gonna zoom in here takes in an action what do you want for it to have be executed inside of it we can also pass it in an actual additional argument if you want to and also a function to see if it can execute let's start first with the can execute we just want it to call launch website boom done we also want to then set our save contact command equal to a new command and again here we'll say save contact there we go ah now you may be wondering why did I get that red squiggly well this is a void of launch website and this is an asynchronous task so it's not an action so what I need to go ahead and do is actually call it say async and a weight on it and call the method there we go perfect so now when I run this actual application again will automatically data bind to this launch website command and the save contact command and windows get called it will then call and come down here and I'll open the website or it'll save this contact wait a little bit setting me is busy true and false there for me so here to update it he'll go ahead and launch my website there we go or we can come back and I can save contact and notice that the nice thing here is it's not blocking so it's all asynchronous so it comes back and comes back on the UI throw so it handles that for me automatically which is pretty nice so we've eliminated all of the code in the code mine there's no don't need to implement a click handler or anything like that I could swap in and out my view model but one final thing what if I wanted to disable these buttons automatically when save contact is clicked and I want to wait because essentially if is busy is true I don't want these to be enabled so check this out we're going to come back up to our command where we created it and notice that we have a function that we can pass in right here that's called can execute so this function we can actually say well call this function and it can execute if we're not is busy we're gonna go ahead and copy the same exact thing into our save contact there we go zoom out here so as long as we're not busy we can launch it so it's a simple function in line very simple very simple there now one caveat to this is that Zen reforms doesn't know when to reevaluate this it'll know right away to evaluate it so if I say is busy I set this to true right away and come in and launch this application it'll say hey it is busy so it shouldn't be enabled and these buttons are gonna be disabled automatically same reforms doesn't no actually win to go reevaluate that method you don't really want it to try to reevaluate just magically you want it to be there so oops I think it should be that their view should be correct let's see here so I can go now and actually tell it when do I want it to reevaluate these commands so we want this to be false obviously so inside of here whenever we do this we can say launch a website command dot change can execute and save contact dot change can execute and now we can go ahead and say hey whenever you change in is busy go reevaluate the actual can execute part of that command so again let it spin up again here so now when I say say if contact notice that it automatically Gray's out right there perfect it does both of them so it's coming in it's saying is busy has changed and it's saving the contact and that's it so you you can put that there you can put it in the method down here wherever you want it to evaluate but since we know it's gonna be bounced this is busy it's one simple place and that's really great because I don't need to do yet another data binding for isn't able to a converter of is busy is not busy anything like that it's just one simple place in this instance it's great because it is busy but you can do data-binding say only when it's equal to this thing or that thing or when best friend then enable this other part of the user interface that's there so a command not only will execute a method but then also enable or disable the actual functionality on the page awesome so we've gotten started we've seen a few things now where do you go to get everything else when you go to developer salmon comm this is gonna take it all the documentation for xamarin iOS Android and also xamarin forms Samra forms there's a great book by charles Petzl to cover everything in xamarin forms but just go right here to the zamel area right here this will handle your binding properties attached properties sam'l basics compilation previewer it's there that's where you went ahead for all the other advanced things that you can do in xamarin forms with this great data binding that you now have great knowledge of perfect so this was a quick introduction to data binding and the mvvm architecture I love mvvm all my apps are built in mvvm type of way because I can then give some UI to a designer they can do the data binding they don't care about the co behind that's back there now there's a lot of other advanced things that you can do like I said value converters you can bind to other control properties that are out there you can do a crazy adjustments on perform it's crazy all the awesome things that you can do in the sam'l with data binding so head over to the documentation for a really deep dive but for now I'm James Monta magno and this has been the zamarons show you
Info
Channel: Microsoft Developer
Views: 81,727
Rating: undefined out of 5
Keywords: channel9
Id: GZDQptTQZsk
Channel Id: undefined
Length: 30min 39sec (1839 seconds)
Published: Thu Aug 30 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.