Skip to main content

Xamarin Forms: XAML Creating Custom Controls The MVVM Way

Intro

For a growing UI page there always comes a need to create sub views that can be used inside a bigger view, and for that we need custom controls, which are controls that are derived either from a layout or a simple view which is the basic control for almost any UI component in Xamarin forms, and therefore for a start i will use that as an example.
And in such example we will create a custom control with a set of bindable properties and explain how they work, also how to add an event that can also be bound to Commands

Lets Create the control 

I have just went ahead and created a custom control that inherits from Xamarin.Forms.View and have some properties such color and checked all properties to be bound to by the ViewModel serving as the datacontext of the this control. here is the code below


using System;
using Xamarin.Forms;

namespace UserControls
{
    public class CustomView : View
    {
        public Color Color
        {
            get ;
            set ;
        }

        public bool Checked
        {
            get ;
            set ;
        }
    }
}


And For the Above code we see we have a few properties that can be set from the xaml code like for instance as below



<ContentPage
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:controls="clr-namespace:Avira.Afm.Forms.Controls;assembly=Avira.Afm.Forms"
    xmlns:contentViews="clr-namespace:Avira.Afm.Forms.Views;assembly=Avira.Afm.Forms"
    x:Class="Avira.Afm.Forms.Views.MainPage"> 
    <Grid HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" RowSpacing="0" ColumnSpacing="0">
<controls:CustomView Checked="{Binding Checked}" Color="{Binding Color}"/>
</Grid>
</ContentPage>


While this could be valid from the first glance but if you know xaml you know that this will never work as there is no way the UI will know how to map the values to these properties, and that is why we have the Dependency properties,

Dependency Property:

Is a property that acts as an observer for other properties that are mapped to the UI notifying from and to UI the changes that happen to this property to the type that defined that property, and how it is implemented ? 
it is like as follow for instance the two properties we have 



using System;
using Xamarin.Forms;

namespace UserControls
{
    public class CustomView : View
    {
        public static readonly BindableProperty ColorProperty = BindableProperty.Create(propertyName: nameof(this.Color), returnType: typeof(Color), declaringType: typeof(CircleButtonView), defaultValue: Color.White);

        public static readonly BindableProperty CheckedProperty = BindableProperty.Create(propertyName: nameof(IsMouseOver), returnType: typeof(bool), declaringType: typeof(CircleButtonView), defaultValue: false);

        public Color Color
        {
            get { return (Color)GetValue(ColorProperty); }
            set { SetValue(ColorProperty, value); }
        }

        public bool Checked
        {
            get { return (bool)GetValue(CheckedProperty); }
            set { SetValue(CheckedProperty, value); }
        }
    }
}


Dependency properties must be static and read-only because they can only be set once
The setters and getters of the Mapped properties should be updated to update the corresponding dependency properties, also casting needs to be done because dependency properties are always dealing with objects.
After this update we can have the XAML code working

now for how to use events ?

Custom Events 

In Order to have an active even first we need to define the eventhandler  and the handler that will invoke it. and it should be as follows and then we can user the the even to behavior command to do bind the event to the commands in Xaml



 public event EventHandler Clicked;    
 protected virtual void OnClicked(EventArgs e)
 {
    Clicked?.Invoke(this, e);
 }

That's it for this one :)



Comments

Popular posts from this blog

(AsyncWebClient) Async Webclient for windows phone 8

Using windows phone web client is pretty common but the thing is you can not use it using Async -> Await mechanism so i used threading to create an async functionality for The Download string and upload string methods here is the code below // Comment public class AsyncWebClient { public Task DownloadString(Uri uri) { var task = new TaskCompletionSource(); try { var client = new WebClient(); client.DownloadStringCompleted += (s, e) => { task.SetResult(e.Result); }; client.DownloadStringAsync(uri); } catch (Exception ex) { task.SetException(ex); } return task.Task; } public Task UploadString(Uri uri, string content) { var task = new TaskCompletionSource(); try { var client…

RuntimeBinderException cannot resolver property in Unit Test in case of dynamic return.. Solved

Xamarin UI Tests – Deep dive Part 1

IntroAs the title may describe this is the first of the series of articles that will cover the UI Test of Xamarin in a deep dive, we will start simple and then dig deeper as we go. Since this is very well the first of the series, it will mostly cover up the architecture and the testing technique that Xamarin UI Tests uses.

The Technology
Xamarin UI Test is an automation testing framework similar to selenium, Watir, Watin (.net), Robot and Sikuli, if you have used BDD (Behavioral Driven Development) or a more advanced TDD (Test Driven Development) approach at least you must have come across one of these frameworks, and in that perspective comes Xamarin UI Testing as an automation framework designed specifically for Xamarin Automation testing, For starter Xamarin UI Tests was not build from scratch, instead it was built on top of another UI Automation testing framework that is targeting android and iOS sepecifically which is Calabash, I have to say that this choice was made wisely as of n…