开发者

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


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.


I don't believe there is a way of accomplishing exactly what you need with your current converter. As you mentioned, you could do the calculation in your ViewModel, or you could change your converter into an IMulitValueConverter.

From your specific scenario (the converter tied to a ViewModel class, and a few of its properties), I would lean towards implementing the logic in the ViewModel.


Hmm, you don't show the full implementation. But I think it should update, if the value bound to the GUI provides the PropertyChanged-Event.

Regards

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜