Is there a clean and/or an accepted standard way of referring back to the ViewModel from an IValueConverter, or does that break the MVVM pattern? Basically, I want to convert bound data in the UI based on other properties of the ViewModel. I guess this is the same question as how do you refer back to the Window/Page from an IValueConverter since a reference to the control is not passed to the Convert/ConvertBack methods.
问题:
回答1:
I would suggest adding a new property to the ViewModel that concatenates or combines the other properties in the ViewModel. This eliminates the need for an IValueConverter
all together.
Check out this discussion on IValueConverters
when using MVVM.
回答2:
Whenever I have the rare scenario when I need to use multiple properties from a ViewModel in a converter, I just pass the entire view model as the input, ala;
<Textbox Text="{Binding, Converter={StaticResource WholeObjectConverter}"/>
As far as getting a reference to the window / page / view that invoked the conversion is not a good idea as this certainly breaks the MVVM pattern. The idea is that your views, and data are separate entities, and by design should have no knowledge of each other.
If you wanted to really hack it though, you could probably get clever and pass the references that you want (either the ViewModel or the View) as the ConverterParameter part of the binding .