Category Archives: Desktop Development

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.

public event PropertyChangedEventHandler Property Changed;

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

{

if (this.Property Changed != null)

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

}

 

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.

private int myVar;
public int MyProperty

{

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

}

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.

private string _Name;
public int Name

{

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

}

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.

private string _Name;
public int Name

{

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

}

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.

private string _Name;
public int Name

{

get { return _Name; }
set
{

If (Name != value)
{

_Name = value; RaisePropertyChanged();

 }

}

}

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.

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

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

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

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.

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}”/>

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.

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}”/>

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 in UWP

Most applications use more than the standard controls. Many businesses have business practices that makes them unique, so they want these practices implemented in the software, but standard controls are typically too limited or have issues. A good example would be the UWP CheckBox. If you do some research, you will find developers having issues customizing the standard UWP CheckBox so you might want your own check box.

To create a custom native UWP control is actually a very simple process.

Right click on the UWP project, and select Add Item

UWP Custom Native Control by Jeff Wyzard

In the Add New Item Window, Select “Templated Control” 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.

Visual Studio will create a new cs file in the root of your project using the name you gave it in the Add New Item Window. In my example, it added “CustomCheckBox.cs”. The class will be a simple class initially with it setting the DefaultStyleKey in the constructor.

Under a folder “Themes”, you will see a file “Generic.xaml” which holds the basic style and control template.

UWP Custom Native Control by Jeff Wyzard

If you want to have custom properties to use in XAML for your app, then you need to implement the properties as Bindable Properties. Visual Studio has a code snippet for adding Bindable Properties. In your cs file (my file is CustomCheckBox.cs), type “propdp” and hit the tab key twice. 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.

UWP 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 string property named “Text” with a default empty string as the default value.

UWP Custom Native Control by Jeff Wyzard

In the “Generic.xaml” file, now we need to add a text block to print the label for my custom check box. I will add it inside the border.

UWP Custom Native Control by Jeff Wyzard

To get the TextBlock to show the value in our new bindable property, we will give it a “TemplateBinding” and as you are typing in the name, intelliSense will give you a list of bindable properties in your new control. As you can see below, my new “Text” property is on the list.

UWP Custom Native Control by Jeff Wyzard

At this point, our new custom control has a text block with a binding to the Text property in it that will show on the screen whatever string that we put into the XAML when using the control in our project.

UWP Custom Native Control by Jeff Wyzard

To use your custom control in the XAML of your page/control, you will need to declare a namespace to it. If you app was “CustomUWPControl”, then you would add a xmlns of

xmlns:ctrl=”using:CustomUWPControl”

After declaring the namespace, you can use the control in your XAML just like any other control. For my control, I would add

<ctrl:CustomCheckBox Text=”Jeff Wyzard”/>

If you run your app with the new control, you will see the text block with your Text string displayed on the screen.

The ControlTemplate in the “Generic.xaml” can have most any XAML controls or layout that you would want as if you were drawing it out in the xaml of your app. So, you could be a Grid with multiple rows, you can use an Ellipse or other shape methods, etc. in your ControlTemplate to produce a reusable custom control for UWP.

Have fun!

Code is available on my Github at https://github.com/jwyzard/CustomUWPControl

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

My Blog: www.wyzard.us

LinkedIn: https://www.linkedin.com/in/jeff-wyzard-b89a7011