Here's a common scenario - you've got a WPF control bound to a property
that doesn't update when the value of the property changes. If the
object you have access to doesn't implement INotifyPropertyChanged or
use Dependency Properties, this can be a very common problem.
Fortunately for us, there's a fairly simple work-around to this issue.
WPF gives us the ability to force an update to any binding. Let's jump
right in with an example class:
public class MyClass
{
public string MyString { get; set; }
}
As you can see, this object has no way to notify bound controls when a
property changes. Here's some XAML that binds to the property, MyString.
<StackPanel Orientation="Horizontal">
<Label Content="Property Value: " />
<Label Content="{Binding MyString}"
x:Name="_lblValue" />
</StackPanel>
All right, now some code to change the value of the property:
_myClass.MyString = "Some new text.";
What you'll notice is that when the value changes, the Label bound to
the property doesn't update - this is because WPF has no way to know
when the property changes. What we have to do is get a reference to the
binding and tell it to update manually.
BindingOperations.GetBindingExpressionBase(
_lblValue, Label.ContentProperty).UpdateTarget();
GetBindingExpressionBase
will return the base class for all binding expressions. This means that
if you're binding is something complicated - like a MultiBinding, this
will still work. We have to pass the function the target object and
property where the binding is applied. We then simply call UpdateTarget,
which forces the target to update with the source. Once this is called,
our label will display the new value.
I hope this helps someone out there that has encountered this issue.
Source Files:
Comments
Post a Comment