Silverlight Quick Tip: How to force re-binding
Today I’ll show how to do “dirty trick” to force re-binding and as a result UI value updating.
First of all – the reasonable question – “Why force rebinding? Why not use INotifyPropertyChanged mechanism?”
This was my questions also, but the person who asked the question had his reasons: he is using resources (Resx) to localize the application and bind the UI to those resources. Also UI gives user an ability to change the language (and code behind does it by changing CurrentThread.CurrentUICulture). In this case what should be the notification?
The request was to keep binding definition at XAML and at the right time use those definitions to force the re-binding.
My approach was to get the BindingExpression from XAML element, and bind this XAML element to the same binding once again – this forces the binding
Sample code:
BindingExpression bindExp = txtSTR1.GetBindingExpression(TextBlock.TextProperty);
Binding bind = bindExp.ParentBinding;
txtSTR1.SetBinding(TextBlock.TextProperty, bind);
And this is actually works
Live demo here
Sources here
Enjoy,
Alex