Category Archives: Xamarin

Data Binding 101 with WPF, UWP and Xamarin Forms

Data Binding is a major part of XAML that has been used in Windows WPF, Windows UWP and Xamarin Forms. The biggest benefit with data binding is that it synchronizes your data between your data source and the UI. Changes to the data source will automatically be pushed into the UI and optionally have changes from the UI pushed back to the data source.

The data source must be set in the UI so the binding framework knows the object for the data source. The property that must be set in the UI varies depending on the framework. For WPF and UWP the property is DataContext and for Xamarin Forms the property is BindingContext. The UI object will retrieve the data source from its own property if the property is set. If the UI object DataContext or BindingContext is not set, the binding will look to the UI parent. If the UI parent is not set then it will look at the UI parent’s parent and continue up the tree to the top UI object.

The C# object that is assigned to the UI DataContext or BindingContext needs to inherit from INotifyPropertyChanged. You might need to add a using System.Component Model to be able to use the notify property change.

Any data source properties that will be used for binding need to call the property change notification framework. I use the code block below to implement the INotifyPropertyChanged interface. The first line implements the property changed event. Then we create a method RaisePropertyChanged to check that the property changed event has been hooked.

[pullquote]

public event PropertyChangedEventHandler Property Changed;

private void RaisePropertyChanged([CallerMemberName] string caller = “”)

{

if (this.Property Changed != null)

this.PropertyChanged(this, new PropertyChangedEventArgs(caller)):

}

[/pullquote]

 

The above code method RaisePropertyChanged has one parameter for the name of the property that is changing. We have the parameter defaulted using the code argument [CallerMemberName] in front of the parameter to the name of the property calling the method.

Visual Studio has code snippets that helps you create a property by typing “propfull” and hitting tab twice. Visual Studio will create the code below. The code below includes a field default name of “myVar” and a property with a default name of  “My Property”. Both are defined as an int with the type in the field, the name of the field and the name of the property highlighted allowing you to change them by typing over the defaults and use the tab key to go between each highlighted area.

[pullquote]

private int myVar;
public int MyProperty

{

get { return myVar; }
set { myVar = value; }

}

[/pullquote]

If you were wanting a string field to hold someone’s name, then I would change the myVar to _Name while changing the type int to string and change MyProperty to Name. See sample code below.

[pullquote]

private string _Name;
public int Name

{

get { return _Name; }
set { _Name = value; }

}

[/pullquote]

By default, a property can be used for binding but the value of the property will only be used initially so if the value of the property changes, the UI object will still be using the initial value. To get the UI object to show the updated value then we need the property to call property changed notification. To do this we call the RaisePropertyChanged method in the setter of the property. See the same code below.

[pullquote]

private string _Name;
public int Name

{

get { return _Name; }
set { _Name= value; RaisePropertyChanged(); }

}

[/pullquote]

A lot of apps stop with the above for implementing property change notification but it does something that tends to create extra UI processing at times. The property changed notification is called every time the value is set for the property. That is not a big deal except if the same value is assigned the property change notification is called causing updates to the control which do not need to be made. A simple solution would be to check the new value against the existing value of the property while only updating the field and calling the property change notification if the value is different. See code below.

[pullquote]

private string _Name;
public int Name

{

get { return _Name; }
set
{

If (Name != value)
{

_Name = value; RaisePropertyChanged();

 }

}

}

[/pullquote]

The example above shows a typical simple property for using in data binding.

You can implement binding to your UI object in your C# code or XAML, right now I’ll be showing how to implement the binding in XAML.

Next step would be to discuss the options for implementing the binding in XAML.

To use the property for displaying the Name property in a label, you would put bracket Binding Name and closing bracket inside quotes for the property.

[pullquote]

WPF example
<Label Content=”{Binding Name}”/>
Or
<TextBlock Text=”{Binding Name}”/>

 UWP
<TextBlock Text=”{Binding Name}”/>

 Xamarin Forms example
<Label Text=”{Binding Name}”/>

[/pullquote]

The binding in XAML can have several parts to it but if you just put the name of the property then it defaults the one and only value after the keyword Binding to the “Path”. So, the example above is the same as the following.

[pullquote]

WPF example
<Label Content=”{Binding Path=Name}”/>
Or
<TextBlock Text=”{Binding Path=Name}”/>

UWP
<TextBlock Text=”{Binding Path=Name}”/>

Xamarin Forms example
<Label Text=”{Binding Path=Name}”/>

[/pullquote]

The above example shows one way binding to the label so if the value of the property changes and the property change notification is called then the label would be updated.

Another argument on the binding is mode. Mode shows you to specify how the binding works. OneWay tells the system data flows from the source to the control and is updated by property change notification. OneWayFromSource tells the system to update the data source from the control. OneTime tells the system to update the data source from the control one time and not update even if property change notification is called. TwoWay tells the system the system to update the data source from the control and from the control to the data source.

For mode, you will probably use TwoWay a lot since it is used with most data entry controls in XAML. The TwoWay mode tells the binding to put anything enter by the user into the property in your C# class.

[pullquote]

WPF
<TextBox Text=”{Binding Path=Name, Mode=TwoWay}”/>

UWP
<TextBox Text=”{Binding Path=Name, Mode=TwoWay}”/>

Xamarin Forms
<Entry Text=”{Binding Path=Name, Mode=TwoWay}”/>

[/pullquote]

The above explains basic data binding. Binding has several other parameters that you can use to format the data and bind to other controls or other objects. I will explain more about those later.

 

Creating a custom native control using Xamarin.iOS

A lot of apps need more customized UI than what is available with the current set of controls. Today we’ll add a customized Check Box control since iOS does not have a Check Box. Some suggest that you use the Switch control as a replacement for the Check Box, but when developing custom apps and the client or boss want a check box, then I tend to implement a check box while others say it cannot be done. I’ll show the basics of creating a custom control for iOS of a check box.

Right click on your Xamarin iOS project and select Add Item.

Creating a Custom Native Control by Jeff Wyzard

In the Add New Item Window, Select “UIView” and give it a name for your custom control. After giving your control a name, click the Add button so Visual Studio add the file(s) to your project.

We need to modify the register attribute on the class to add DesignTimeVisible(true)

Creating a Custom Native Control by Jeff Wyzard

Now we will add any properties that we’ll need for customizing our new control and we’ll use the Visual Studio code snippet “propfull”. In the class, type propfull and hit the tab key twice.

Creating a Custom Native Control by Jeff Wyzard

Visual Studio will add some code to your class with default type of int and named “MyProperty” with the property type, name, name of the class and default value highlighted

Creating a Custom Native Control by Jeff Wyzard

You can change the different highlighted options and press the tab key to go from one highlighted option to another. In my case, I wanted a Boolean property named “IsChecked” with a default false as the default value.

Creating a Custom Native Control by Jeff Wyzard

We need to add an attribute Export with the property name and the property will be browsable.

Creating a Custom Native Control by Jeff Wyzard

Now we can start drawing portion of the custom control. Type override and select the Draw method with the CGRect argument since we’ll need to override the Draw method for the drawing.

Creating a Custom Native Control by Jeff Wyzard

Next in the Draw, we can draw the box for our check box control.

Creating a Custom Native Control by Jeff Wyzard

You can do whatever you need to do in the Draw method to create your custom control.

Have fun!

Follow me online to learn about creating Xamarin Forms custom view that uses these custom native controls.
My Blog: www.wyzard.us
LinkedIn: https://www.linkedin.com/in/jeff-wyzard-b89a7011

 

Creating a custom native control using Xamarin.Android

A lot of apps need more customized UI that what is available with the current set of controls. Today we’ll add a customized Check Box control since the Android Check Box has some limitation.

Right click on your Xamarin Android project and select Add Item.

Creating a custom native control using Xamarin.Android by Jeff Wyzard

In the Add New Item Window, select “View” and give it a name for your custom control. After giving your control a name, click the Add button so Visual Studio add the file(s) to your project.

Add a line to register the new control with an attribute on the class that registers the namespace plus name of the control.

[Register(“ComponentTrak.UI.Droid.TrakCheckBox”)]

 public class TrakCheckBox : View

    {

Now we will add any properties that we’ll need for customizing our new control and we’ll use the Visual Studio code snippet “propfull”. In the class, type propfull and hit the tab key twice.

Creating a custom native control using Xamarin.Android by Jeff Wyzard

Visual Studio will add some code to your class with default type of int and named “MyProperty” with the property type, name, name of the class and default value highlighted

Creating a custom native control using Xamarin.Android by Jeff Wyzard

You can change the different highlighted options and press the tab key to go from one highlighted option to another. In my case, I wanted a Boolean property named “IsChecked” with a default false as the default value.

Creating a custom native control using Xamarin.Android by Jeff Wyzard

For Xamarin Android controls, if the property will be changing something on the screen then you will need to tell the View to refresh by calling Invalidate(); method on the set of the new property.

Creating a custom native control using Xamarin.Android by Jeff Wyzard

If you do not have an attrs.xml file in the Resources/Values folder then you will need to add a new XML file by right clicking on the Values folder and selecting Add New Item. In the Add New Item window, select Data on the left and XML File in the middle. Give the new XML File a name of “attrs.xml” and click the Add button.

Creating a custom native control using Xamarin.Android by Jeff Wyzard

In the new XML file, we need to define the properties that we’ll be using to customize the new control. First we’ll need to add a tag of “resources” and inside the resources tag, we’ll need to add a tag of “declare-styleable”. The declare-styleable tag will need an attribute of name that is the name of the new control.

Creating a custom native control using Xamarin.Android by Jeff Wyzard

Inside the declare-styleable, we will add a line for each of our custom properties. So we’ll add a attr tag with attributes of name and format. The name attribute is the name of the property and format will be the type of property.

Creating a custom native control using Xamarin.Android by Jeff Wyzard

In the constructor of the new control/view, we will need to get the values.  I perform this in the Initialize method and pass the context and attrs into the Initialize method. Using the context and attrs variables that are passed into the constructor, we obtain an array of the property values. Use the context, obtain a styled attribute and the method will return a TypedArray.

Creating a custom native control using Xamarin.Android by Jeff Wyzard

Next we’ll get the value if defined in the layout and we’ll give the method a default value so if the control property is not given a value in the layout. Using the typedArray instance that we call a Get method based on the type. In my example, I’ll call GetBoolean to get the boolean value for the IsChecked property.

Creating a custom native control using Xamarin.Android by Jeff Wyzard

After getting the values, we need to call recycle.

Creating a custom native control using Xamarin.Android by Jeff Wyzard

Now we can start drawing portion of the custom control. Type override and select the OnDraw method with the Canvas argument since we’ll need to override the OnDraw method for the drawing.

Creating a custom native control using Xamarin.Android by Jeff Wyzard

Next in the OnDraw, we can draw the box for our check box control.

Creating a custom native control using Xamarin.Android by Jeff Wyzard

You can do whatever you need to do in the Draw method to create your custom control.

Have fun!

Follow me online to learn about creating custom native controls in Xamarin and iOS plus Xamarin Forms custom view that uses these custom native controls.

Follow me
My Blog: www.wyzard.us
LinkedIn: https://www.linkedin.com/in/jeff-wyzard-b89a7011

 

Getting the Xamarin Certified Mobile Developers Badge

In December of 2016, I decided that I wanted the Xamarin certification since more of my development projects were on iOS, Android and UWP mobile devices. I am now a Xamarin Certified Mobile Developer as of January 1, 2017.

I wanted to share my experience with Xamarin University and certification testing. I am also Microsoft C# Certified Professional, so that saved time in learning portions of C# that some coming from web technologies would need to learn. Since I’ve been developing with WPF when it was an add-on to Visual Studio 2005, working with XAML, XAML styles, triggers, templates, etc. made the move to Xamarin Forms easier.

If you are a developer who has been wondering about the Xamarin University classes and if they are worth it, the answer is emphatically, YES! Xamarin development tools have never been documented very well, in my opinion (I hear the same comment from other developers), so finding out how to do different routines was a matter of finding the right blog or forum.

Xamarin University has classes on more than the Xamarin tools, which is great. Some of the classes cover using 3rd party tools with Xamarin like SQLite, Azure, C# and classes are mostly 2 to 3 hours each. There are different instructors offering most of the classes at different times of the day/month so a class at one time is bad for you, they probably offer it again at a different time, so no matter where you live or your work schedule, a class should be available. The classes were structured very well with slides, exercises and the instructors, at times, even had flash quiz or two. Most all the instructors were nice, tried to involve the students and were great about answering questions plus at the end of the classes, they would hang around to make sure they answered any questions about the class. If you had questions related to the topic that they could not answer about the class, they followed up very quickly.

The certification exam is much better coverage of the programming matter than other exams that I have taken over the years. Other exams tend to focus on new features or items that the company believes are import even if you do not use those features in your career. I do think the Xamarin certification exam could be improved by removing the opinion based questions where there are multiple methods to accomplish the same goal instead of asking which is better based on one person’s opinion. In the real world, “which is better” will depend on other factors which the test is not able to take into consideration. The Xamarin Certification Exam Study Guide is extremely helpful.  Be sure to review it since some material covered on the exam is not covered very well in the certification classes.

Overall the classes and exam were a great and fun experience, highly recommended and  I give it two thumbs up!