Xamarin Forms Tutorial: Build Native Mobile Apps with C#

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

This is very timely. I just starting looking into developing with xamarin. Thank you for sharing

👍︎︎ 10 👤︎︎ u/Jgsirois 📅︎︎ Dec 22 2016 🗫︎ replies

Can't decide if i should use Xamarin or continue with React Native -_-;. I love C# because it's strongly typed and the code is easier to read for me...but the hype around React Native is sucking me in

👍︎︎ 5 👤︎︎ u/wh00a 📅︎︎ Dec 24 2016 🗫︎ replies

They already fixed ListView extreme lag on Android?

👍︎︎ 3 👤︎︎ u/melanke 📅︎︎ Dec 22 2016 🗫︎ replies
Captions
so what is a marine forms thyroid forms is a library that enables you to build native apps for iOS Android and Windows using a single c-sharp codebase if you have any experience with Windows presentation foundation or Silverlight xamarin forms will be very familiar to you so we have this xml-based language called sam'l which stands for extensible application markup language and we use this to define the user interface of our applications for example we can define what elements we have on a page where they are located and what do they look like behind every sam'l file we have what we call a code behind which is basically a class that implements the behavior for that page for example what should happen when we click a button or select an item from a list so these are the responsibilities of the code behind now in terms of architecture xamarin forms is built on top of two existing libraries Sam rendered Android and xamarin iOS so with some reforms we worked with a single unified API for creating user interfaces and xamarin forms will internally map these user interface elements to their corresponding native equivalent and this makes our applications completely native so we don't have user interface elements that look the same across different platforms if you use a button that button looks different depending on where you run your application also because zaman forms is built on top of some rendered android and hammering that iOS you can write platform specific code that uses the API exposed by any of these libraries so you're not limited to a common set of features that are available across all these platforms now the first question that a lot of beginners ask me is maash do I need to know about examined on android or examined iOS in order to learn xamarin forms none at all the only exception is if you want to write something specific for Android or iOS otherwise for the most part you can learn xamarin forms on its own the second beginners question is how do I know which xamarin products should I use should I use them in forms or one of the more specific libraries the answer is it depends what makes a marine forms powerful is the ability to share most if not all your code across these platforms so you code the application once and then build it for different platforms this building is nothing more than just a compile in Visual Studio that's all you have to do so if you don't need to use much of the platform specific functionality and code reuse is more important to you then go for examine forms otherwise if you're going to do a lot of customization and have quite a few use cases for working with platform specific API then it's better to use surrender the Android or examined on iOS in terms of tooling you have a few options here if you have a Windows machine you can build and deploy apps to Android and Windows but not I Oh s for that you need a Mac either a MacBook Pro or an iMac on the other side if you're a Mac user you can build apps for Android and iOS but not for Windows so if you want to target all platforms you need both a Windows and a Mac machine but this is not a requirement to take this course or to learn zarion forms in general it's all about where you want to deploy your application you can start with a Windows machine and use Visual Studio to build apps for Android and Windows if in the future you want to build your app for iOS you just add a Mac to your setup and you're pretty much done you don't need to write any new code you just build your project for iOS alright next I'm going to show you how to set up your development environment in this video I'm going to show you how to set up xamarin on a Windows and a Mac machine I'm going to start off by setting up on Windows and then I'll get to Mac whether you're a Windows or a Mac user be sure to watch this video thoroughly so if you're a Windows user you probably have Visual Studio so we can install xamarin and that will install all the required SDKs as well as project templates in Visual Studio so simply head over to xamarin comm slash download fill out this form and be sure to set the answer of this question I already have Visual Studio installed to yes so you don't get Visual Studio you only get xamarin installer once you run it you're going to see a dialog box like this be sure to select the following items on the cross-platform mobile development so the latest version of c-sharp slash net xamarin so you see I've currently installed version 4.0.3 but there is a newer version so I'm going to take that and then under common tools and software development kits select Android native development kit you see I have installed both the 32-bit and 64-bit versions you also need to install Android SDK and then you need to install at least one of Android SDK setups the difference between these items are there version number so we see the first item is API level 19 and 21 and the last one is API level 23 you can go for the last version or if you have enough space on your machine you can install all of them apache ant is not really necessary but i have installed it anyway and finally you need to select java SE development kit now if you have a typical machine and are not part of a network with a proxy server this installation process goes very smoothly but it may fail if you're behind a proxy server or if you're running Windows in a virtual machine on a Mac this happens mainly because xamarin installer cannot download some of the required resources so at this point you need to manually install some of these components I've attached a PDF to this lecture with more details about manual installation so hopefully you won't have any problems during the installation but if you encounter any issues you really need to troubleshoot them yourself because every machine is different in terms of the hardware and software and I really cannot help you with that so just google the exact error message you get and you will definitely find a solution I just want to emphasize do not get discouraged if you get any errors you only need to spend a bit of time to travel through these issues and then everything is going to be fine also it would be really helpful if you post the errors you get and the solutions you find in the discussion board because I can get all these various errors and compile them into a PDF and that would be very valuable resource for future students of this course now what if you're a Mac user you have two options you can either use xamarin studio on a Mac which is a lightweight ide similar to visual studio or you can use Visual Studio but this requires a Windows machine in my set up I'm running Windows as a virtual machine using VMware which option is better samer in studio is the fastest option you simply head over to zombocom slash download and get xamarin studio and you're good to go we can build apps for iOS and Android but not for Windows if you want to target Windows you need a Windows machine so you can either get a physical machine or use a virtual machine like me then you need to follow the same steps to install Sam rein on your Windows machine in this video I'm going to show you how to create a xamarin forms app in Visual Studio whether you're a Windows or a Mac user watch this video thoroughly so here I am using visual studio 2015 let's create a new project under visual c-sharp templates select cross platform for xamarin forms apps we have two options here portable class library or shared assets the preferred way and the best practice recommended by xamarin is a portable class library if you want to understand the differences between these two project types I'll attach a PDF for you for further reading but read it after watching this video so let's go ahead with this portable class library I'm going to call our application hello world okay now this process is going to take a few seconds so I'm going to pause the recording okay next you're going to see this dialog where we select the target and minimum version for Universal windows apps a universal Windows app can run under Windows 10 or Windows 10 mobile without the need to be written for each I'm going to accept the defaults here okay our solution is ready now before looking at the structure of this solution as a best practice whenever you create a new salmon forms app right-click the solution and go to manage NuGet packages for solution then go to the Updates tab and make sure to select all packages and update them because ambereen frequently releases new libraries okay as part of this update process one of the older packages is going to be uninstalled and for that you need to restart Visual Studio so we're start yes okay all the packages are updated properly now let's see what we got here so in this solution we have six projects the first one is our portable class library and this is where we're going to do most of the work so all the code that should be shared across different platforms should be written here and if you look inside we only have one class app which is the starting point of our application next we have five platform specific projects one for Android one for ILS one for Universal windows apps which can run on Windows 10 or Windows 10 mobile and one for Windows 8.1 and the last one for Windows Phone 8.1 so anytime we want to write platform specific code will write it in these projects as I explained before the whole idea about xamarin forms is about code reuse we want to write code that can run across different platforms that's why we do most of our work in the portable class library all these projects you see here have a reference to this class library now if you don't have a Mac you're not going to see this iOS project here also let's say you only want to build an app for Android and don't care about other platforms you can simply delete these projects here and if in the future you decide to support them you can simply right-click the solution add a new project let's say you want to target iOS then under iOS expand it universal and here is the blank app template so you just add a project to your solution and you're good to go okay now let's run this app you can see that currently hello world that droid is set as the startup project so if I press ctrl + f5 is going to be loaded in an Android emulator here on the toolbar you can see the list of emulators installed on my machine these emulators come as part of installing xamarin so if everything goes well during the installation you should see quite a few emulators here but in my case because I'm running Windows in a virtual machine on a Mac I had to manually all Android emulators if you want to deploy and debug your application on a real device you need to set it up for development first and then you can see it listed here so you simply select it and then press control f5 to deploy and run the app on your device or f5 to debug it and these are the shortcuts that we always used in c-sharp development I've attached the PDF to this lecture with additional details about setting up your Android or iOS device for development now let's run this app control f5 now the first time you launch Android emulator you're going to wait quite a few minutes even up to 10 or 15 minutes depending on your hardware so please be patient and here is my Android emulator and you can see our first summer informs app is running successfully so this app is just a single page with a label in the middle of the screen now your emulator may look different in terms of its size and the controls you have here but all these are settings that can be changed when creating an emulator manually now let's say we want to run this app in an iOS simulator so we right-click the iOS project and set it as a startup project then on the toolbar I can either deploy to my device because I have an iPhone or use one of these simulators iPhone 4 5 6 ipad and so on now this simulator actually runs on my Mac not on the windows and here on the toolbar we have this icon xamarin Mac agent if you don't see this toolbar go to the View menu under toolbars select iOS we also have a toolbar for Android but I have disabled it for now so with this xamarin Mac agent we can select the Mac on our network that is responsible for launching the simulator so visual studio talks to as a Marine agent on a Mac in order to launch a simulator in most cases your Mac should be automatically detected but if not you can simply click add a Mac add the IP address here and you're good to go just remember you need to install Sam rain both on your windows and on your Mac machine now I can press control f5 and this will launch my iPhone simulator on my Mac okay and here's the same app running in an iOS simulator next I'm going to show you how to create a summary forms app using xamarin studio alright now I'm going to show you how to create a xamarin forms a pin xamarin studio on a Mac if you're a Windows user you can skip this video but I encourage you to watch it just to get familiar with what your development environment on a Mac would look like so here I'm using xamarin studio version 6 and I have changed my theme to dark let me show you how to do it so on the top xamarin studio Preferences under visual style set the interface theme to dark alright now let's create a new solution under multi-platform category select app and then forms app next I'm going to call this hello world you can see both Android and iOS are checked but we don't have a checkbox for windows because in xamarin studio you can the target Windows and for that you need Visual Studio now in terms of the shared code the default setting is unused portable class library the other option is use shared library which is not something I would recommend again if you want to know the differences between a portable class library and shared assets look at the PDF I'm attached to this lecture next I'm going to accept the defaults here which are about location version control and test clap so nothing important at this point create okay our project is ready and this is much faster than Visual Studio now as I told you in the last video as a best practice whenever you create a new xamarin forms app make sure to update all the packages so right-click the solution and go to update new get packages you can see xamarin studio is updating the packages and this is going to take a little while okay all packages are successfully updated now similar to visual studio you can see that the iOS project is set as the start of project because it's bold and here on the toolbar we can select a simulator so we've got various versions of iPhone and iPad or we can deploy to a real device now to run this application you press command alt and enter and then iOS simulator launches and loads our application if you want to try the Android app right click this project and set it as startup project now you see all the Android emulators here so throughout this course I'll be using xamarin studio to do my development because it's much faster and more lightweight if you want to use visual studio that's perfectly fine all the code I'm going to write in this course is exactly the same and it doesn't matter which IDE use it's entirely your personal choice alright next we're going to explore this application in more detail and add a bit of functionality so you will see both zamel and code behind in action alright this is what I'm going to build now I want to add a new page to our app with a button in the middle of the screen in iOS buttons don't have a border they look like labels so when we click this button we get an alert so let's go ahead and implement this all right as I explained in the last lecture I'm going to use xamarin studio in this course to doing my development if you want to use Visual Studio that's perfectly fine all the code I'm going to write is exactly the same so as I told you earlier in summary in forms we use samo which is an xml-based language define the visual appearance of our app and we use code behind to implement how the user interface behaves so I'm going to right click our portable class library and add a new file on the left side select forms and on the right side select forms content page samo and now we give this a name greet page if you're using Visual Studio again right click the portable class library add a new item in the list of templates select cross-platform and here select forms zamel page and call it greet page so this will add two new files to our project one is greet page that's ammo and if you expand it here's the code behind which is just a simple c-sharp class and we have the same scenario in xamarin studio so here's our code behind and here's our sam'l file as you can see sam'l is based on XML the root element here content page represents the type of our page in xamarin forms we have a few page types we have content page master detail page navigation page carousel page and so on we use content page to present some content to the user whether that being text images or the combination of the two now let me break up this line so you can see more clearly in our content page element we have a couple of XML namespace declarations the first one is owned by xamarin and this namespace is for elements that have no prefix like this content page element so this element belongs to xamarin to xamarin forms we have another namespace declaration which identifies a prefix so this : x syntax is used to declare a prefix and if you look at the URI assigned to this XML namespace you can see that this namespace is owned by Microsoft which represents the standards mo that Microsoft introduced in year 2009 now what is this : X here that means any elements or any attribute that is prefixed with an X belongs to this namespace look at this attribute the class attribute it's prefixed with an X and we call it X class so this attribute belongs to the Microsoft namespace now look at the value assigned to this attribute it's hello world that greet page which is the fully qualified name of our code-behind class so if we switch to the other tab look the name of our class is greet page and it's placed in hello world namespace so using X class attribute we establish a link between the sam'l file and the code-behind file now remove the content of this content page element and instead let's add a button so button I want to put this button in the middle of the screen so we set horizontal options to Center and vertical options to Center next we set the text attribute click me so this way we zamel we are defining the visual appearance of our page now what about the behavior when we click this button I want to display an alert in xamarin forms buttons have an event called clicked so we set clicked to a string and this identifies the name of the method in the code behind that should be called when this event is raised you can see they are in studio or Visual Studio is suggesting a name for this method handle underline clicked so we press Enter that brings us to the code behind press ENTER again and that generates our event handler so this event handler as you see it's a private method because it doesn't have an access modifier like public it has two arguments one is an object which is the sender or source of the event and the second one is event args which brings additional tales about an event if this method looks strange or unfamiliar to you I highly recommend you to watch my c-sharp advanced course because there I have a complete lecture on events and handlers now I want to change the implementation of this method to display an alert we call display alert method we inherit this method from content page class which is the base class for our greet page so the arguments will supply here is the title of the dialog box the message we want to display like hello world and then label for the cancel button let's just call this okay potentially we could supply another argument if you want to have two buttons like okay and cancel or yes and no but for this video we don't have to worry about it now in terms of clean coding we should keep the constructor of our classes on the top so I want to move this method down okay we are done with this new page now we want to make sure that this page is displayed when our app is started so back to our solution view in the portable class library you see we have a file called apt sam'l let's expand this here's our code behind you can see here main page property is set to a new instance of hello world page main page is a property that is defined in the basin class and we use that to set the starting page of our application so I'm going to change this to new greet page now let's run this enzyme rain studio I'm going to press command alt and enter in Visual Studio you press ctrl + f5 but before doing so make sure in the solution Explorer set one of these platform-specific projects as the startup project I'm going to use iOS you can use whatever you want so let's run the application okay here's our bun so now you have an idea of what it's like to build cross-platform apps using xamarin forms so you have seen Dameron forms in action and you know that with xamarin forms you can build native apps for different platforms but you might be curious how's a Marine actually achieves this so let me give you a bit of background alzheimer in products like samurai on android xamarin that iOS examining forms are built on top of mano which is an open-source version of.net that runs on various non Windows platforms like Linux UNIX and OSX mono is a project that has been around since pretty much as long as dotnet itself but it wasn't very popular until recent years in the mana world we had two releases one was called mana for Android which was later renamed to xamarin that Android and the other release was mono touch which is now what we call xamarin iOS both these libraries give you access to the dotnet base class library so you have the same namespaces you are familiar with you got the same classes with the same interfaces but they also give you access to the native API on their platform so you have access to additional assemblies and namespaces that mimic the ones that come natively with Android and iOS these are the classes that Objective C or Java developers work with when they build native apps for Android and iOS when using xamarin that Android or examined on iOS we work with these classes just like standard Seashore classes in dotnet and these libraries will internally call the corresponding API on the target platform now how that happens it's pretty complex and it's not something we need to worry about that's something that developers at xamarin have to deal with now that you have an understanding of xamarin that Android and stammering that iOS let's get a little bit more specific here when you build an application with xamarin Android xamarin sushar compiler compiles down your c-sharp code to intermediate language or IL it also emits the mono runtime with your application this mono runtime is similar to CLR that you should probably be familiar with so when you launch an Android app this runtime is loaded into the memory and then it gets your il code and compile it to the native code for Android and this process is what we call just-in-time compilation or JIT this is the same mechanism that is in place when you build a regular dotnet application with c-sharp when you build a console desktop or web application the same magic happens now with iOS we have a different story Apple does not allow cheating so when you build your iOS application zamarons you sharp compiler first compiles your sushar code down to IL and then it uses apple compiler to compile it to native code and that's why you need an apple machine so the output is native code that iOS can understand and there's no cheating involved here in other words when you ship your application there is no model runtime embedded in your application so this is how xamarin on android and xamarin that iOS work but what about xamarin forms well zerrin forms is built on top of these two libraries so we have this assembly called xamarin dot form score and here we have classes that define a common unified API to work with different platforms for example we have a class called button and this is the button that we reference in sam o or in code behind now we have another bunch of platform-specific assemblies that map these common objects in zaman forms to the corresponding native equivalent let me show you so here in this blank solution let's expand this portable class library now under references under front packages look we've got xamarin that forms the core and this is the assembly that defines that common API that we worked with so here we've got classes like bun label list view page and so on now if you look at one of the platform specific projects like the Android one gained under references from packages now here we have an assembly called xamarin that forms the platform that Android and this is the assembly that is responsible for mapping those common controls we have in xamarin that forms that core into their corresponding Android equivalent and in this assembly we have a bunch of what we call renders so these are the classes that know how to render for example a label or a button now we have the same architecture in other projects so let's expand the iOS project references from packages now look we've got xamarin that forms the platform that iOS so this is how xamarin forms works all right let me quickly give you an overview of how I have structured this course and where you will find the content you are looking for in the next section you're going to learn the basics of Zemo and this gives you a good foundation to progress through the rest of the course next we're going to look at layouts which we use for arranging visual elements on screen so you will learn how to build user interfaces like these next you're going to learn about images you will learn about downloading images from the internet or embedding them in your applications you will also learn about icons after that we're going to look at lists so you will learn how to present data in beautiful interactive lists following that we're going to look at navigation you will learn how to navigate users from one page to another how to implement master detail how to implement tabs how to display pop-ups and so on next you're going to learn how to accept input from the user and this will help you build forms and setting pages but we are not going to talk about saving or loading settings in this section that's the topic for the following section so in data access section you will learn various ways you can store application data you will learn about application properties you will learn about file system you'll learn about boring structured data in a sequel light database and finally you will learn about consuming restful services now if you don't know what restful is all about don't worry I've got some PDFs for you so you're in good hands next we're going to look at mvvm architectural pattern I will explain what mvvm is when you should use it and why and how to implement it but briefly we use mvvm for decoupling our application from a presentation framework like xamarin and we do this for testability so at the end of this section I've got a short video where I show you how to unit test your view models more on this later and finally in the last section you're going to look at some more practices and features that are useful in building larger complex applications and in this section I will show you some of the useful plugins that you can use to access common device functionality like using the camera GPS checking the status of the battery detecting motion accessing contact book and so on so there is a lot to cover over the next seven hours and I hope by the end of watching this course you will have a very solid foundation to build cross-platform mobile apps using xamarin forms [Music] well hello it's mash here I hope you've been enjoying watching my salmon forms tutorial in case you didn't know this tutorial is the first hour of my comprehensive seven and half hour course on udemy in this course you will learn how to build native mobile apps for Android iOS and windows with c-sharp if you're interested to have this course you can get it with a big discount using the link in the video description and if not that's perfectly fine continue watching as the next section is coming up so as I explained in the last section samo is an xml-based language that we use to define the visual appearance of our applications we're going to use them a lot throughout this course so in this section you're going to learn samo in more detail and by the end of this section you will have a good foundation that will help you progress through the rest of the course so let's get started okay continuing from the project we created in the last section in our greet page first I'm going to delete this button and then in the code-behind I'm also going to remove this event handler now back in the salmon file I want to put a label on the page so label I want to put it in the middle of the screen so horizontal options center vertical options Center and text hello world now we can create the same UI using code instead of zamel let me show you how so back in the code behind in the constructor after the call to initialize component we can set the content property of our page this property is derived from content page which is the base class for our greet page now we can set this to a new label and set its properties here so horizontal options we set this to layout options which is an enumeration that's Center similarly for vertical options the center and finally text now don't worry about this red line under initialize component I think there's something wrong with my xamarin studio now that aside you can see that we can create user interfaces using code as well in this case I'm setting the content property to a new label and this is exactly equivalent to what we put between opening and closing tags of content page element now you might ask maash why do we want to create user interfaces in the code as opposed to sam'l well in more than 90 percent of the cases it would use samo you would use code only if you want to add elements on a page dynamically for example depending on different circumstances you may want to add a label or a button or a slider or whatnot and all this can happen dynamically but as I said this is the kind of behavior that most applications don't exhibit so all I want you to take away here is that if you want to put elements on a page dynamically you can do it in the code now why is that better than the code because it's cleaner and less noisy look at these properties here horizontal options and vertical options we're simply setting them to your string value Center now look at the equivalent in the code we have to prefix this value with layout options the name of the enumeration so there is a little bit of noise in the code and this can get worse when you're dealing with complex hierarchical structures in those situations sam'l is a definite winner because XML is naturally hierarchical now the reality is even when we use demo at runtime we have a sam'l parser that reads this demo file and it will instantiate objects just like the code we have written here so the exact same code will be executed by the sam'l parser let me show you when it happens so in the solution I'm going to right click the solution and set display options to show all files if you look at the object folder under debug we have a file here hello world that greet page that zamel the G which stands for generated dot C s so this class is automatically generated for us we can see it's a partial class so part of that is here and the other part is in the code behind you can see here we have a call to initialize component method now you might think this method is inherited from content page but no it's not there it's defined in this generated code look it's here and inside this method we have a call to load from zamel so when we compile our our application our example files are embedded in our assembly and at runtime when initialize component is called this sam'l file is extracted from the assembly and pass to the sam'l parser then sam'l parser will take that sam'l and generate a user interface like this all right so for now I'm going to delete this code here and we're just going to stick to sam'l for creating user interfaces next I'm going to talk about content property all right now let me show you something I want to put a slider below this label slider but if I run this application now we only see the label not the slider but why is that all right let's have a look at xamarin documentation to figure out why so I'm going to search for examine content page class [Music] you alright look at the Declaration of content page class this class is decorated with an attribute called content property and in this attribute we have a string which specifies one of the properties of content page in this case the name of that property is content and you saw that in the last lecture we set the content property to a new label remember now let's look at the Declaration of the content property look here's the content property its type is a view view is the base class for all our visual elements like buttons labels sliders and so on so because the type of content is view we can set it to an instance of a single view not multiple views that's why we cannot have multiple children or multiple widgets or multiple views inside content page element so what's the solution let me introduce you to a new element stack layout and then I'm going to move these two widgets inside stack layout with stack layout we can stack multiple widgets horizontally or vertically now I want to make sure both the label and the slider are in the middle of the screen so I'm going to grab these two properties horizontal and vertical options and apply them to stack layout now let me run the application again and here's the result so here's our label and here's the slider now let's inspect stack layout class so we search for xamarin stack layout class look this class derives from layout of view now if you look at the Declaration of layout class you can see the content property attribute again and look the name of the content property for the layout is children so let's look at the children property now if you scroll down you're not going to see that children property you have to navigate up the hierarchy so we go to the layout class and layout class implements a layout controller let's look at this interface now look at the children property it's of type I you read only list so these children property because it's a kind of list it can contain multiple widgets and that's the reason we can use a stack layout to stack multiple widgets on the screen alright next we want to take this application to the next level so we want to add this behavior such that when we move this slider the label is updated to show the current value of the slider alright now we want to take this application a little bit further so we want to add this behavior such that when we move the slider the label is updated to show the current value of the slider to implement this we need to handle the value change event of this slider and then in our event handler we can get the current value and then set the label so pretty basic in the first section you saw an example of handling the click event of a button in xamarin forms so the technique we are going to use here is exactly the same for the slider we handle the value changed event and set this to the name of a method in our code behind so enter enter now I'm going to move this down okay inside our event handler we can use this e argument passed to this method to get the new value of the slider but we need a reference to the label so we can set its text how do we do it well back in our demo I'm going to give this label a name or an ID so we use one of the attributes defined in Microsoft namespace so X colon name this X is a prefix which is declared in the XML namespace declaration for Microsoft namespace so this name attribute belongs to the standards ammo that Microsoft introduced in 2009 and it's applicable in other frameworks that use ammo like Silverlight or Windows presentation foundation or xamarin forms now we set this name to an identifier like label now when I save this file and go back to the code behind I can type label dot and here we have access to our label so we can set the text property I'm going to use string that format value is provide an argument here and then set it to e dot new value now the value we get here is a floating-point number between zero to one and there are a lot of digits after decimal point so I would like to format this value to fix point with two digits after the decimal point so let's run the application okay now if I move the slider look the value is updated and this is a pattern that you see in a lot of real-world applications but the value may be displayed as percentage that there is just one tiny problem with this application let me restart it the label is displaying hello world instead of the current value of the slider to fix this in the constructor after the call to initialize component we can explicitly set the value of the slider so again we need a reference to this slider object so back in our sample file we use X name attribute and give it an identifier slider save now back in the code-behind we can type slider dot value you can set it to 0 or 0.5 whatever let's run the application again okay that's much better now let me give you a bit more insight about this X name attribute so under the object folder debug open up hello world that greet page the demo the G that's CS look we have two private fields here one is label the other is a slider and in initialized component method after the call to load from Zemo these private fields are initialized so we have this method find by name which is inherited from content page the base class of our grid page and we give this method an argument which specifies the name or the identifier for our widget with this after initialize component we can access this private field like in this case the slider just remember if you put this line before initialize component you're going to get a null reference exception because that private field is not initialized at that point so in this lecture you learn how to access element in code behind using X name attribute now even though our application is fully functioning but there is a simpler and cleaner way to implement the exact same functionality and that's called data binding which I'm going to show you in the next lecture all right now let's see how we can use data binding to implement the same behavior data binding is a concept that you see in a lot of UI frameworks like WPF and Silverlight and even in web applications we have frameworks like angular and knockout and many others that provide this concept of data binding basically what it means is that we bind a property of a user interface element to a property of another object in this case we want to bind the text property of the label to the value property of the slider so when the value of the slider changes the text property of the label is automatically updated with this we don't have to manually handle the value change event of a slider which means we don't need to create this event handler either so our code would be cleaner and more maintainable internally the framework itself will create this event handler based on our binding expression so let's see how we can do this first of all I'm going to remove this event handler and back in zamel I'm also going to remove the value change the attribute of slider now we want to bind the text property of the label to the value property of the slider so we need to use a special syntax for this so far all the attribute values you have seen have been strings at runtime these strings are converted to a primitive type or an object using a type converter in case of data binding we cannot convert a string value to a binding expression that's why we need a special syntax and example this is called sam'l markup extensions so we use curly braces to instruct sam'l parser that this is not a string literal and it's a mark of extension there are many different markup extensions available in zamo and in this video you're going to learn two of them the first one is binding so curly braces binding now to set up binding we need to specify what object we want to bind the text property to so we set source to now here we want a reference to the slider object that's when we use another markup extension so again curly braces now this mark of extension is called X reference so X colon reference and we use that to reference another object in this demo file note that is prefixed with X which means this belongs to the standards ammo that Microsoft introduced in year 2009 if you work with other saml-based frameworks like WPF or Silverlight you would see this now after X reference space we need to specify the name of the target element in this case slider and this is based on the value of X name attribute all right so here's the source object now what property of this object are we interested in the value property which represents the current value so after source comma path equals value we call this path instead of property because that property itself may be an object and we may want to use the dot notation to access another property like a dot B dot C that's why it's called path alright that's pretty much all we have to write now if we run this app this is what we get note the label previously we formatted this number with two digits after the decimal point so let's go ahead and do this back here so in our binding expression we have set up source path and now the third property string format equals and we use single quote to differentiate from double quotes for the value of the text attribute now here we supply a standard c-sharp string format so value is curly braces zero represents the first argument colon f2 for formatting now let me break this up into multiple lines okay this is cleaner and more maintainable now let's run the application again okay that's exactly like before now let's take this to the next level what if we also want to bind the opacity property of the label to the value of the slider so let's try another binding expression opacity we use curly braces for markup extensions the first mark of extension is binding now here we need to specify the source object equals another markup extension we use ex reference to reference the slider then we set the path to the value property of the slider now we don't need a string format because opacity is just a number between 0 to 1 now let me run this application and here's the result note that the label is a little bit grayed out and if we move this slider to the left it becomes transparent or if we go to the right it becomes opak but look at our binding expression these bindings are a little bit noisy in both cases you are using the slider as the source object so let me show you how to remove this noise and make this code a little bit cleaner and more maintainable we can set the binding context attribute of the label to our slider so again we use markup extension X reference slider now slider will be the source object for any properties of the label which means in our binding expressions for the text and opacity properties we don't need to repeat this line remove remove also we can take this to the next level and remove path equals value and just add value like this so we can put this on the same line binding to value and same here definitely cleaner now let's take this to the next level I want to add a box view the box view is a box filled with a color so above the label I'm going to add a box view set its color to let's say green and again I want to bind its opacity property to the value of the slider so opacity equals markup extension binding we set the source another binding expression x reference slider and pass a closed value let's run this application okay here's the result again you see there is a little bit of duplication in this code both the box view and the label are referencing the slider as they're binding context so we can basically move this binding context set up from the label to our stack layout the container for box view and the label and this will be inherited by all the elements inside stack layout which means we can simplify this binding expression for the opacity of the box view remove the source and the path so this is how we set up data binding now finally we don't really need this X name for the label because we have not referenced it anywhere so we can delete it all right next I'm going to show you how to deal with device differences all right now let me show you something don't type anything just watch for the stack layout I'm going to remove vertical options attribute let's run this application in Android and see what happens okay this is what we get note that the box view is on top of the page just below the blue bar now I'm going to run the same app in iOS okay and this is what we get again note where the box view is located in Android our page started right below the blue bar but in iOS our page starts right from top of the screen so if you had some text here instead of box view that text would clash with the current time so this is one of the key differences between Android and iOS in this video I'm going to show you how to add some padding to top of the page but only in iOS so back in xamarin studio in this video i'm going to show you how to do this in code-behind and then in the next video i will teach you how to achieve the same thing in zamel the reason I want to introduce you to code behind is so that you have better understanding of what happens under the hood so we have this class called device and this has a static property called OS which is an enumeration of type target platform so we can check if target platform is iOS then we set padding of the page which we inherit from content page class to a new thickness object thickness has a few different constructors and the one I'm going to use now takes four arguments left top right and bottom it's good to remember this order because you're going to use this a lot so left 0 top 20 0 and 0 so with iOS we always want to add 20 pixels on top of our page so the content of the page does not clash with the standard bar on top of the screen now even though this code is perfectly fine let's just assume you want to have different padding's for android and windows so if you want to use the same technique you would end up writing code like this else if device that OS equals target platform Android something like this now don't worry about these numbers these are just arbitrary now I want to show you a cleaner way to write the exact same code this device class has a method called on platform and this method has to overload one that is generic as you see here and the other that takes actions I'm going to start with the generic one because it's easier to understand so we supply the generic parameter in this case I want different thickness objects for different platforms so the generic parameter is thickness now we can supply different thickness objects for different platforms and to make the code cleaner we can use name parameters in c-sharp so i OS new thickness also you can see that thickness here is grayed out so we can refactor this code and remove it now compare this code with what we wrote earlier we don't have all these if else if else if the code is cleaner and more focused so internally in this method on platform you're actually going to have code like what you see on the top so this method takes care of all these conditional statements and returns the proper thickness object based on the current operating system so then we can get the result from this method and assign it to padding we can use this on platform method with pretty much any objects in this case we are interested in thickness in your applications you might be interested on an integer being different across different platforms then you would supply three integer arguments now as I explained earlier this on platform method also has a non-generic overload let me show you how that one works so the device that on platform I'm going to use the non-generic overload you can see here we have four parameters and they all are optional because they are set to null so let's say I want to execute some code only on iOS then I can supply the name parameter here iOS and here I need to specify an action so I'm going to use a lambda expression for that like this now if you're not sure what this all means you really need to watch my C sharp Advanced Course because I've talked a lot about lambda expressions and actions there so here in this block we can write the code that we want to be executed on iOS for example we can set padding to thickness object this is another way to set the padding property also for discussions sake let's say we want to have a different piece of code to be executed on Android then we set the name parameter action use a lambda expression and here we write the Android specific code so this is how we use device done on platform method whether the generic overload or the non generic one as I explained before we aim to use zamel to define the visual appearance of our applications so in the next lecture I'm going to show you how to use on platform in Java all right now let's see how we can set padding using zamel so in the last lecture you learn that padding is a property of the page and we can set it to a thickness object like this and obviously this applies to all platforms now if you want to apply this padding using zamel we can easily do so like this so for our content page element we set the padding attribute to a string literal now at runtime zamel parser will get this string and give it to a type converter which will parse this into a thickness object and again this will apply to all platforms now what if you want to apply this only to iOS then we need to use an element called on platform on platform and this element has attributes like iOS Android and so on but the problem is we cannot use this element as the value of the padding attribute because these values as you have seen so far are either simple strings or zamel markup extensions but they cannot be an XML element that's when we use a special syntax in demo called property element syntax let me show you how it works so first I'm going to remove this attribute now inside content page element I'm going to add another element content page dot padding so I'm using an XML element instead of an XML attribute to set the padding property and that's the reason this syntax is called property element syntax because we set C char properties using XML elements not attributes now inside this element I can either add a simple string or I can add another element to represent a complex object in this case I want to use on platform element so I can take this here and move it right here now this on platform element maps to a c-sharp class let me show you so back in code behind I'm just going to declare a temporary variable new on platform so this is a generic class and here we need to supply the generic parameter so I'm going to use thickness here now this class has properties like Android iOS and so on now I can get this on platform object and assign it to padding there will be an implicit conversion between on platform object and thickness object okay so we want to achieve the same thing in samo when creating this on platform object we need to specify the generic argument so we use another attribute here X type arguments and we set this to thickness again to emphasize because this is prefixed with X it belongs to Microsoft namespace and it's part of the standards ammo that was first introduced in year 2009 so this line in zamel is exactly like this line in c-sharp okay now we need to set properties of our on platform object so back in sam'l for iOS I'm going to use 0 2000 and to refresh your memory these numbers represent left top right and bottom in the last video I refer to these numbers as pixels but the reality is it's not a pixel for now for simplicity imagine these are pixels so now using this technique I can apply various padding on different platforms I can apply another padding for Android and similarly for Windows if you ever need to so to recap this video we property element syntax when we are dealing with complex objects that cannot be represented using simple strings all right in this video I'm going to show you how to catch and prevent zamel errors so as an example I'm going to remove this s here now let's run this application and see what happens so the application launches terminate immediately and currently I have no idea what's going on here in situations like this the first thing you should look at is application output tab in xamarin studio I believe in Visual Studio this tab is called output now if you look at this tab you see we have a sam'l parse exception the exception says type on platform not found so basically what's happening here is we don't have an on platform type that is not generic so this is one way to find the exception another way is to run the application in debug mode in Visual Studio you press f5 instead of ctrl and f5 and xamarin studio you press command and enter instead of command alt and enter another option is to press this play icon on the toolbar so let's run this okay we got the exception so we got the zamel parse exception and the exception message is type on platform not found now the problem we currently have is that we will not know these exceptions until runtime and as we're typing Zemo it's quite possible that we may make a few mistakes here and there so is there a better way to catch these errors yes there is we can include our sample files as part of compilation so they will be compiled into intermediate language or il and this has a number of benefits the first one is that we can catch errors at compile time instead of runtime the second benefit is that because sam'l files are compiled into il the size of final assembly will be reduced because these ml files will not be embedded in the final assembly and finally compilation of zamel files but slightly optimize the load and instantiation time for sam'l elements now compilation is disabled by default and we need to enable it but that's pretty easy let's go to the solution under properties you find assembly info and here we have attributes that apply to the assembly as a whole like the title the version copyright information and so on we can include another attribute here brackets assembly : and this prefix means this attribute is applied to the whole assembly zamel compilation now we get a red underline here because we need to resolve the namespace so on top of the file using xamarin forms zamel now the parameter to this attribute is an enumeration called zamel compilation options the default value is scheme so I want to set this to compile and that's all we have to do now if I build the application again look we got an error and here's the exact same error we got at runtime but now we're catching it at compile time so this is a pretty good attribute to always include in your assemblies but just in case you need to disable it on a particular sam'l file you can simply go to the code-behind for that sam'l file for example let's say we want to disable this on greet page so we go to the code-behind import the name space using xamarin forms sam'l and then apply the attribute to the class sam'l compilation compilation options skip all right we're done with the basics of sam'l now it's your turn so in the next lecture I'm going to give you some exercises all right now it's your turn I want you to use what you have learned in this section and build a simple application like this so this is a cool application we've got this bun on the top to navigate through different quotes and these are decodes by Einstein now when building this application you don't necessarily have to use the code I've used here you can use simple string values like quote 100 200 3 the point here is that you have limited number of cores in your application and as you click Next when you get to the end of the list and you start over we also have this slider for changing the size of the text so before you get started look at the PDF I'm attached to this lecture all the best and I'll see you in the next section [Music] ok you seem to be very enthusiastic about learning zaman forms so once again if you're interested to take my seven and a half hour course with a discount click the link in the video description I hope to see you in the course [Music]
Info
Channel: Programming with Mosh
Views: 861,817
Rating: 4.9112225 out of 5
Keywords: xamarin forms tutorial, xamarin tutorial, xamarin, xamarin forms, c#, .net, ios, android, windows, mobile, visual studio, c# programming, learn c#, code with mosh, programming with mosh
Id: 93ZU6j59wL4
Channel Id: undefined
Length: 72min 17sec (4337 seconds)
Published: Wed Dec 21 2016
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.