Search This Blog

Thursday, February 9, 2012

Silverlight set Binding to property from code-behind or ViewModel

There is a static class BindingOperations which has a method called SetBinding().

BindingOperations.SetBinding(targetObject, TargetObjectClass.AttachableProperty, new Binding());

Where:

targetObject – is the instance of the object we bind to
TargetObjectClass.AttachableProperty – is the static reference to the propety we want to bind from
new Binding() – is the Binding with the Path and Source properties appropriately set.

Sample usage is:

BindingOperations.SetBinding(observableResources,ObservableResources.CurrentCultureProperty, new Binding() { Path = new PropertyPath("CurrentCulture"), Source = LanguageManager, Mode = BindingMode.TwoWay});

You can also use:

targetObject.SetBinding(TargetObjectClass.AttachableProperty, new Binding());

1 comment:

  1. To use these methods "TargetObjectClass" has to inherit from DependencyObject,

    public class TargetObjectClass : DependencyObject
    {

    }

    ReplyDelete

If you like this post, please leave a comment :)