Search code examples
wpfdata-bindingdatacontextpropertychanged

WPF Update Binding when Bound directly to DataContext w/ Converter


Normally when you want a databound control to 'update,' you use the "PropertyChanged" event to signal to the interface that the data has changed behind the scenes.

For instance, you could have a textblock that is bound to the datacontext with a property "DisplayText"

<TextBlock Text="{Binding Path=DisplayText}"/>

From here, if the DataContext raises the PropertyChanged event with PropertyName "DisplayText," then this textblock's text should update (assuming you didn't change the Mode of the binding).

However, I have a more complicated binding that uses many properties off of the datacontext to determine the final look and feel of the control. To accomplish this, I bind directly to the datacontext and use a converter. In this case I am working with an image source.

<Image Source="{Binding Converter={StaticResource ImageConverter}}"/>

As you can see, I use a {Binding} with no path to bind directly to the datacontext, and I use an ImageConverter to select the image I'm looking for. But now I have no way (that I know of) to tell that binding to update. I tried raising the propertychanged event with "." as the propertyname, which did not work.

Is this possible? Do I have to wrap up the converting logic into a property that the binding can attach to, or is there a way to tell the binding to refresh (without explicitly refreshing the binding)?

Any help would be greatly appreciated. Thanks! -Adam


Solution

  • The workaround here was to add a property to my object (to be used as the datacontext) called "Self" , which simply returned

    public Object Self { get { return this; }}

    Then in the binding I used this property:

    <Image Source="{Binding Path=Self, Converter={StaticResource ImageConverter}}"/>

    Then when I call

    PropertyChanged(this, new PropertyChangedEventArgs("Self"))

    it works like a charm.

    Thanks all.