views:

35

answers:

1

I've found few solutions which assumes that I have 2 or 3 binding objects(or data templates) - that is not good solution for me. Is there an easy way to do this? I can think of cycling through the visual tree and set the binding that way but still this solution doesn't look very neat.

Thank you in advance.

+1  A: 

You can write a custom attached property for this that changes the binding and attach it to the UIElelement where you want to change the binding. All you would have to do now is to trigger a change to that attached property whenever the binding is supposed to change. In the property changed eventhander of your attached dependency property you have access to the UIElement.

<TextBlock local:Helper.DynamicBinding="{Binding SomeStatePropertyOfTheCurrentDataContext}" />

And in the changed eventhandler method:

private void OnDynamicBindingChanged(DependencyObject sender, PropertyChangedEventArgs args)
{
     var senderButton = sender as TextBlock;
     if((args.NewValue as string) == "MainText")
     {
        // bind to the property "MainText" of the current datacontext now 
     }
     else if((args.NewValue as string) == "OtherText")
     {
        // bind to the property "OtherText" of the current datacontext now 
     }
}

However if you come across the need of changing the binding at runtime like this, chances are that your overall design can be improved!

bitbonk
Thanks, it looks like this will solve my problem. I need to change the binding because I am doing automation testing of binding capabilities of a user control.
Koynov