Wednesday, 30 June 2010

Binding Modes in Silverlight

There are 3 binding modes in Silverlight (identified by the BindingMode enumeration):

  • OneTime - bindings update the target with the 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. When the binding is created, the target property is updated from the source.

In OneWay or TwoWay bindings, the source object must implement INotifyPropertyChanged in order for the target to update when the source changes.

For TwoWay bindings, changes to the target do not automatically propagate to the source, except if the binding target is the Text property. In that case, the update happens only when the TextBox loses focus. In other words, the in-memory object to which the TextBox is bound isn’t modified until the TextBox loses focus whereas other elements perform their updates immediately (e.g. the user moves a bound slider control). If you need a TextBox to update as the user types you must implement an event handler on the TextBox TextChangedEvent. For example:

private void myTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
    BindingExpression exp = myTextBox.GetBindingExpression(TextBox.TextProperty);
    exp.UpdateSource();
}

For OneTime and OneWay bindings, calls to SetValue automatically change the target value and delete the binding.

See:

0 comments:

Post a Comment

By all means leave a comment. I may not be able to get back to you as quickly as I'd like but I'll do my very best.