Skip to end of metadata
Go to start of metadata

Data binding provides a simple and consistent way for applications to present and interact with data. Elements can be bound to data from a variety of data sources in the form of common language runtime (CLR) objects and XML. ContentControls such as UXButton and ItemsControls such as UXListBox have built-in functionality to enable flexible styling of single data items or collections of data items.

On this page:

Connecting User Interface Elements With Data

Every binding must specify a source and a target. The following illustration shows the basic concepts of a binding.

The binding engine gets information from the Binding object about the following:

  • The target UI property that displays and possibly allows user changes to the data. The target can be any DependencyProperty of a FrameworkElement.
  • The source object that contains the data that flows between the source and target. The source can be any CLR object, including the target element itself or other UI elements.
    If the target is in a data template, the source can be the UI element to which the template is applied.
  • The direction of the data flow. The direction is specified by settings the Mode property on the Binding object. The optional value converter that applies to the data as it is passed. The value converter is a class taht implements IValueConverter.

The following example shows how to bind Image and Content of a GlassLabel to a value using data binding. The binding source is property of the MainPageViewModel class.

Model
View Model
View

This example is using MVVM pattern that utilize the binding concept. To learn more about MVVM see MVVM Pattern Overview.

The binding is created in XAML using the {Binding ...} syntax, the source is set by setting the DataContext property. In this sample the data context is set to UserControl.

Data context is inherited. If you set the data context on a parent element, all its children will use the same data context. A child element can override this behavior by setting the Source property on its binding object or by setting its DataContext which will then apply to all its children.

You can also use the ElementName property to specify the binding source. The ElementName property is useful when you are binding to other elements in your application such as when you are using a Slider to change the value of a TextBox.

XAML

You can bind a property of the source object by setting the Binding.Path property. The Path property supports a variety of syntax options for binding to nested properties, attached properties, string indexers.

Direction of Data Flow

Each binding has a Mode property, which determines how and when the data folows. There are three types of bindings as follows.

  • OneTime bindings update the target with source data when the binding is created.
  • OneWay bindings update the target with the source data when the binding is created and anytime the data changes. This is the default mode.
  • TwoWay bindings update both the target and the source when either changes. Alternately you can disable automatic source updates and update the source only at times of your choosing.

In order for automatic target updates to occur, the source object must implement INotifyPropertyChanged interface.

Change Notification

In order for changes to the souce object to propagate to the target, the source must implement the INotifyPropertyChanged interface.

INotifyPropertyChanged has the PropertyChanged event, which tells the binding engine that the source has changed so that the binding engine can update the target value.

In the following sample MainPageViewModel class implements the INotifyPropertyChanged  interface.

View Model

To get change notification for collections bound to an ItemsControl, implement INotifyCollectionChanged in addition to INotifyPropertyChanged. If you implement INotifyCollectionChanged, changes to the collection such as adding or removing object will propagate to the target. To get property change notification for objects in collection, the objects must implement INotifyPropertyChanged.

Updating the Data Source

In TwoWay bindings, changes to the target automatically update the source, except when binding to the Text property of a UXTextBox. In this case, the update occurs when the UXTextBox loses focus.

You can disable automatic source updates and update the source at times of your choosing. For example, you can do this to validate user input from multiple controls before you update the bound data sources.

To disable automatic source updates, set the UpdateSourceTrigger property to Explicit. This setting affects all bindings that use the same Binding object (for example, when using an inherited data context). You must update the source for each binding individually, however. To update a binding, first call the FrameworkElement.GetBindingExpression method of a target element, passing in the target DependencyProperty. You can then use the return value to call the BindingExpression.UpdateSource method. The following example code demonstrates this process.

XAML
C#

Binding to Collections

A binding source object can be treated either as a single object whose properties contain data or as a collection of objects. For example, you might want to display a list of items, such contacts info. To do this, use an ItemsControl and repeat over a DataTemplate to display each item in a collection.

XAML

You can enumerate over any collection that implements IEnumerable. If you want the target to update the ItemsSource when the collection changes, implement INotifyCollectionChanged. For more information on change notification, see the Change Notification section earlier in this topic.

Data Validation

Silverlight / WPF supports simple data validation in TwoWay bindings for target-to-source updates. It will reports a validation error whenever the Validation.Errors attached property of a binding contains errors.

Errors are added to this collection in the following cases:

  • Exceptions are thrown from the binding engine's type converter
  • Exceptions are thrown from th binding objects' set accessor
  • Exceptions are thrown from a validation attribute that is applied to a data object or member
  • The binding object implements IDataErrorInfo and its Item property return a value that is not null or Empty.
  • The binding object implements INotifyDataErrorInfo and its GetErrors method returns a value that is not null. The GetErrors return value can change as result of the completion of asynchronous validation operation.

The visual feedback will be provides for validation errors in the following cases:

  • The ValidatesOnExceptions property value is true
  • The ValidatesOnDataErrors property value is true. However, the ValidatesOnDataErrors property is ignored for a source property if the ValidatesOnExceptions property value is true and the source property setter throws an exception.
  • The ValidatesOnNotifyDataErrors property is true. This property can work in combination with ValidatesOnExceptions and ValidatesOnDataErrors.

To receive notification that a validation error has occurred or has been resolved, you must set the NotifyOnValidationError property to true on the binding object. This tells the binding engine to raise the BindingValidationError event when a validation error is added to or removed from the Validation.Errors collection. For example, you can handle the error event to log the error or provide additional visual feedback.

The following example shows how to provide custom binding validation using ValidatesOnExceptions.

View Model
View

This example is using MVVM pattern that utilize the binding concept. To learn more about MVVM, see MVVM Pattern Overview.

After the sample starts, type in letters instead of numbers to get an error caused by the type converter. Type in a negative number to get an error from the source object's set accessor. Type in a positive number to resolve the validation error. UXTextBox target-to-source updates occur only when the UXTextBox loses focus. The button is provided to change the focus. If you prefer, you can update the source manually in response to the button click, as described earlier in the Updating the Data Source section.

Data Conversion

Often you many need to display data in format that differs from how it is stored. For example:

  • Storing a null value, but dispalying a friendly default value
  • Storing a color as an RGBA value but dispalying it as a string name
  • Storing a number as floating-point but display it as a currency value
  • Storing a boolean value but using it as Visibility enum

You can create a converter for this kind of data binding by creating a class that inherits from IValueConverter. The following example shows how to create a ColorConverter that can display the color of a rectangle in its RGBA string representation and convert it back to RGBA value when the string is changed.

C#
XAML

Binding to Commands

Binding can also be used to bind commands to controls that implements ICommandSource. To learn more about commanding see Commanding Overview.

Using Advanced ClientUI Binding Framework

ClientUI Binding Framework provides a set of functionality to perform binding on some specific scenarios that are not currently supported in Silverlight platform. ClientUI also includes a cross-platform multi-binding capabilities which allows you to attach multiple data binding on a single dependency property. For more information, see Introduction to Multi Binding.

The following are several scenarios that you can achieve using the ClientUI Binding Framework.

  • Binding to specific ancestor element type at specific anchestor level range.
  • Specify binding within the control style
  • Clear error after text input during validation

Using Binding Descriptor

BindingDescriptor has three modes of binding that you can choose from, they are FindAncestor, FindName and Self. Each of this mode has different purpose and different settings.

FindAncestor

FindAncestor is used to bind the target with a specific ancestor element type defined in specific ancestor level range. This mode is commonly used when you know that a specific ancestor element type existed on certain level.

In this mode, you specify the AncestorType to determine the type of the target that will be bound and the AncestorLevel to determine how far it will look up for the ancestor with types specifed in AncestorType.

The default value of AncestorLevel is 1, so it will look at up one time and check whether the current ancestor match the type specified in AncestorType. If it matches, it will continue with the binding process.

The following example shows how to use FindAncestor mode to bind the elements inside ItemTemplate of a UXListBox to UXListBoxItem as their ancestor.

XAML
C#

This sample bind the Visibility property of StackPanel to the IsSelected property of UXListBoxItem using FindAncestor. Notice that the BindingDescriptor also supports IValueConverter as discussed in previous section.

FindName

FindName is used to bind the target with an element with specific name. In this mode, you specify the ElementName that the target will be bound to.

The following example shows how to use FindName mode to bind the target with an element with the specific name specified in ElementName property.

XAML

This sample bind the Value property of UXProgressBar to MainContainer Width property using FindName.

Self

Self is used to bind the target within itself. You can bind one property with other property within the same element using this mode without needing to specify element name each time.

The following example shows how to use Self mode to bind Text property of UXTextBox to its BorderBrush.

XAML

Using Property Binding

The XAML binding that uses {Binding ...} syntax cannot be defined in the Setter markup of Style because the Setter is not a dependency objeect. ClientUI Binding Framework provides a solution to address this limitation by introducing PropertyBinding.

PropertyBinding enables you overcome the Silverlight limitation so that you can define XAML data binding inside the Style. To understand how the property binding works, see the following example. 

Model
View Model
View

This sample binds the UXListBox to a collection of products. Each product has a category that has different border coloring that bound to the BorderBrush of UXListBoxItem.

Clear Error on Text Input

ClearErrorOnTextInput is an attached property that you can used to enhance validation behavior. The standard validation behavior gives an error indication when the validation failed and stays visibile until a new validation takes place.

ClearErrorOnTextInput provides an enhanced behavior where you can clear the error indication immediately when you perform any text input.

The following example shows difference between input control that uses ClearErrorOnTextInput and input controls that does not use ClearErrorOnTextInput.

XAML