简体   繁体   中英

WPF MVVM Change Model

I have a UserControl where the data gets passed in via a dependency property. The UserControl is backed by a view model and the data is assigned to a property of the view model.

The XAML binds to both properties in the view model as well as properties within the passed in data.

The problem is if the user changes the data then databinding with the UI breaks. The UI is still bound to the original data object.

How can I cause the binding to get refreshed? INotifyPropertyChanged is implemented throughout, but it is not the property that is getting stale, but the binding. Basically, how do you go about replacing a backing model?

Since I'm not sure my description is clear I will try to describe it again in pseudo code.

<MyControl Source="{Binding Data}"/>

Where source is a dependency property of MyControl. In the PropertyChangedCallback this data is handed to the view model.

MyViewModel.Data = Source;

Within the MyControl XAML things are bound to this model.

{Binding Path=MyViewModel.Data.Item}

If you are wondering why the dependency property is defined in the UserControl, it is because it is a reusable control and the end user should not know about the view model.

"The UserControl is backed by a view model" and thus breaketh the application.

The UserControl's DataContext should be the Model. Period. If you need to perform UI logic, do it in the codebehind. Need something else? Create DependencyProperties on the surface of your UserControl to supply them.

When you create a ViewModel specifically for your UserControl, you break the natural flow of the DataContext (at this point, probably the Model the UC is designed to work with) and binding within the UserControl. It's pointless in most cases and harmful in some (as you have noticed).

My canonical answer on the subject contains more details .

Are you trying to swap-out the DataContext of the usercontrol during an application's session?

If you are, then I am fairly confident that this will not work.

Have you considered spinning up a new instance of that user control with the other DataConext?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM