Xamarin.Forms Guides | Samples

Xamarin.Forms.BindableObject Class

Provides a mechanism by which application developers can propagate changes that are made to data in one object to another, by enabling validation, type coercion, and an event system. BindableProperty.

See Also: BindableObject

Syntax

public abstract class BindableObject : INotifyPropertyChanged, IDynamicResourceHandler

Remarks

The BindableObject class provides a data storage mechanism that enables the application developer to synchronize data between objects in response to changes, for example, between the View and View Model in the MVVM design pattern. All of the visual elements in the Xamarin.Forms namespace inherit from BindableObject class, so they can all be used to bind the data behind their user interface elements to View Models that are supplied by the application developer.

To bind the data behind a property in a BindableObject, typically a view, to a property in the View Model, application developers should do the following.

First, the developer creates a pair of properties on the view, one of which is a BindableProperty, and the other of which is a property of whatever type is required. In the code below, MockBindableObject stands in for what would typically be a user interface object in production code. Application developers should note the use of BindableObject.SetValue(BindableProperty,Object) and BindableObject.GetValue to get and set the value on the bound property; The property of the desired type provides the interface that the target of the bound property will implement.

C# Example

class MockBindableObject : BindableObject
{
    // App developers should use the method below in production code for 
    // better performance
    public static readonly BindableProperty BoundNameProperty =
         BindableProperty.Create ("Foo", typeof (string),
                                  typeof (MockBindableObject),
                                  default(string));

    // App developers should use the method below during development for
    // design-time error checking as the codebase evolves.
    // public static readonly BindableProperty FooProperty 
    //     = BindableProperty.Create<MockBindableObject, string> (
    //         o => o.Foo, default (string)
    //     );

    public string BoundName
    {
        get { return (string) GetValue (BoundNameProperty); }
        set { SetValue (BoundNameProperty, value); }
    }
}

Second, the developer creates the implementation for the bound property in a class that implements the INotifyPropertyChanged interface. In the MVVM design pattern, this is typically done by the View Model. Application developers should implement the INotifyPropertyChanged interface on classes that they want to use as View Models. In the example below, app developers should take note of the idiomatic way that the Name property is implemented to, first, ensure that the property actually changed and return if it did not, and only then assign the value and call the BindableObject.OnPropertyChanged method. Additionally, the Name property in the example below merely wraps the name field. In practice, the application developer may choose a different model in which to store application data.

C# Example

class MockViewModel : INotifyPropertyChanged
{
    string name;

    public string Name
    {
        get { return name; }
        set
        {
            // OnPropertyChanged should not be called if the property value
            // does not change.
            if (name == value)
                return;
            name = value;
            OnPropertyChanged ();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    void OnPropertyChanged (string propertyName = null)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
            handler (this, new PropertyChangedEventArgs (propertyName));
    }
}

Third, and finally, the application developer binds an instance of a BindableObject to an instance that implements INotifyPropertyChanged. In the vocabulary of the MVVM design pattern, this is "binding an instance of the View to an instance of a View Model." Once this step is complete, changes in the data are propagated between the View and View Model in a way that is determined by the value of the BindingMode enumeration, if any, that was passed during the binding step.

The code below, when included in a project that reference the classes above, creates an instance of both MockBindable and MockViewModel, performs some intitialization, sets the binding, and then demonstrates a one-way binding. The code below runs without throwing an exception.

C# Example

public static void OneWayDemo ()
{
    var view = new MockBindableObject ();
    var viewModel = new MockViewModel ();

    // Pre-load the ViewModel, for demonstration purposes
    viewModel.Name = "Testing";

    // Create a one-way (default) binding
    view.SetBinding (MockBindableObject.BoundNameProperty, new Binding ("Name"));
    
    // App developers should only set the binding context after all
    // calls to SetBinding() have been made, for performance reasons.
    view.BindingContext = viewModel;

    // In a one way binding, the ViewModel value will be used to update
    // the values in the View during initialization
    if (view.BoundName != "Testing")
        throw new Exception ();

    view.BoundName = "gnitseT";

    // in a one way binding, changes to the View will NOT update the ViewModel
    if (viewModel.Name == "gnitseT")
        throw new Exception ();
}

Requirements

Namespace: Xamarin.Forms
Assembly: Xamarin.Forms.Core (in Xamarin.Forms.Core.dll)
Assembly Versions: 1.0.0.0, 1.1.0.0, 1.2.0.0, 1.3.0.0, 1.4.0.0, 1.5.0.0, 2.0.0.0

The members of Xamarin.Forms.BindableObject are listed below.

See Also: Object

Protected Constructors

Initializes a new instance of the BindableObject class.

Public Fields

static readonly
BindingContextPropertyBindableProperty. Implements the bound property whose interface is provided by the BindableObject.BindingContext property.

Public Properties

BindingContextObject. Gets or sets object that contains the properties that will be targeted by the bound properties that belong to this BindableObject.

Public Methods

ClearValue(BindableProperty)
Clears any value set by BindableObject.SetValue for property.
ClearValue(BindablePropertyKey)
Clears any value set by BindableObject.SetValue for the property that is identified by propertyKey.
GetValue(BindableProperty) : Object
Returns the value that is contained the BindableProperty.
RemoveBinding(BindableProperty)
Removes a previously set binding.
SetBinding(BindableProperty, BindingBase)
Assigns a binding to a property.
SetValue(BindableProperty, Object)
Sets the value of the specified property.
SetValue(BindablePropertyKey, Object)
Sets the value of the propertyKey.

Protected Methods

ApplyBindings()
ApplyBindings(Object)
Apply the bindings to thisBindableObject.BindingContex.
OnBindingContextChanged()
Override this method to execute an action when the BindingContext changes.
OnPropertyChanged(String)
Call this method from a child class to notify that a change happened on a property.
OnPropertyChanging(String)
Call this method from a child class to notify that a change is going to happen on a property.
static
SetInheritedBindingContext(BindableObject, Object)
Sets the inherited context to a nested element.
UnapplyBindings()
Unapplies all previously set bindings.

Public Events

BindingContextChangedRaised whenever the BindableObject.BindingContext property changes.
PropertyChangedRaised when a property has changed.
PropertyChangingRaised when a property is about to change.

Explicitly Implemented Interface Members