Marino Šimić
Marino Šimić

Reputation: 7342

WPF MVVM prevent the binding on SelectedValue to change the value in some situation

I have a viewmodel with a SelectedDocument property and a Documents property.

The Ui has a custom ListView control with ItemsSource bound to Documents and SelectedValue to SelectedDocument on the viewmodel.

Now in the viewmodel in the setter of the selected document in some situation I need to raise a dialog service message asking something, and in case of cancel I need to prevent changing the SelectedDocument.

I can do that but when I don't change the value of the property in the viewmodel I get the UI and the ViewModel out of sync.

It probably has soemthing to do due to the fact that the setter of the property is called when the two way binding is updating the source.

How can this be solved?

Thanks

Upvotes: 1

Views: 1448

Answers (3)

shriek
shriek

Reputation: 5197

You have to undo the change, but you cannot do so directly in the Setter but have to use the Dispatcher as discribed here.

As for using the Dispatcher in MVVM, there are various posts about using an IDispatcher interface for that, as can be found here or here or here (look under the MEFedMVVM.Services.Contracts namespace). You'll have to see which one of those works for you.

Upvotes: 3

Scott
Scott

Reputation: 563

I assume your using .Net 3.5? Its a 'known issue' and has been changed in .Net 4 (note I say changed not necessarily fixed!)

Theres a blog post here about the change, it also points to some suggestions about how to deal with the issue in 3.5

https://web.archive.org/web/20150925210516/https://karlshifflett.wordpress.com/2009/05/27/wpf-4-0-data-binding-change-great-feature/

Upvotes: 1

Martin Doms
Martin Doms

Reputation: 8748

You should call your PropertyChange event event if the dialog is cancelled. This way the UI layer will respond by resetting SelectedDocument.

Upvotes: 0

Related Questions