开发者

How can I change the binding for template elements at runtime?

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.开发者_C百科 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.


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜