WPF Update Binding when Bound directly to DataContext w/ Converter

我只是一个虾纸丫 提交于 2019-11-29 14:48:00

问题


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


回答1:


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.




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/2670606/wpf-update-binding-when-bound-directly-to-datacontext-w-converter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!