views:

31

answers:

1

I have a ListBox bound to a CollectionView which again is bound to a property on a viewmodel.

<ListBox ItemsSource="{Binding Source={StaticResource pumpCurvesViewSource}, ValidatesOnDataErrors=true}" />

Now, the viewmodel implements IDataErrorInfo, but the validation of the property on the viewmodel is never triggered. If I skip the CollectionViewSource and bind directly to the property on the viewmodel, everything works as expected (meaning the view outputs a big red box around the ListBox when its invalid):

            <ListBox ItemsSource="{Binding Path=PumpCurves, ValidatesOnDataErrors=true}" />

Now, how can I get the same behaviour when using a CollectionViewSource?

A: 

If the view model implements IDataErrorInfo, that means that it specifies which properties have validation errors. The properties the ViewModel is aware of, however, are the properties of the ViewModel, not any properties bound to properties bound to the view model. Try putting a CollectionView directly on the ViewModel, and binding to that instead.

GWLlosa
Are you saying that the CollectionViewSource should point to the view model instead of a property on the view model?
Marius
What I'm saying is that the CollectionView should live on the ViewModel instead of pointing to a property on the ViewModel. For example, instead of having a List<string> on the ViewModel that is wrapped by a CollectionView, have a CollectionView on the ViewModel which wraps the List<string>, which can now be private. Then bind your ListBox to the CollectionView on the View Model, rather than to an additional CollectionViewSource created in XAML. That way, since the CollectionView is a property of the ViewModel, it should be covered by the ViewModel's implementation of IDataErrorInfo.
GWLlosa
Ok, but there are sometings I don't like about that. 1: Microsoft doesn't recommend it (http://msdn.microsoft.com/en-us/library/system.windows.data.collectionview.aspx): "..You should not create objects of this class in your code.". 2: CollectionView is not type safe and I want my ViewModels to specify intent, untyped views are bad for that any would also introduce a lot of nasty casting in my unit tests.
Marius
I agree with your objections, actually. I'm hoping that someone else will come along and point out that there's a better way. In the absence of that better way, this is what we've done on our projects to make this work.
GWLlosa
Also, I read "You should not create objects of this class in your code. To create a collection view for a collection that only implements IEnumerable, create a CollectionViewSource object, add your collection to the Source property, and get the collection view from the View property." as saying to not construct CollectionView, but to use CollectionViewSource to create instances, not as a restriction upon using CollectionViews in code.
GWLlosa