开发者

WPF MVVM: View is not reloaded when ViewModel is changed

开发者 https://www.devze.com 2023-02-06 15:39 出处:网络
I have a WPF application based on the MVVM pattern. It has a tree on the left side and a details area on the right side. The tree contains objects of various types and I have a view model for each typ

I have a WPF application based on the MVVM pattern. It has a tree on the left side and a details area on the right side. The tree contains objects of various types and I have a view model for each type. In the view, I have a different data template (containing a user control) for each view model type. The view is then selected via databinding based on the current details view.

Now, when I switch between tree nodes, I also instantiate a new details view model for each node and the view gets changed accordingly, firing both the DataContextChanged event and the Loaded event. That is, until I start to switch between objects of the same type. Here, too, the details view model gets updated, but the view instance stays the same. This means, only the DataContextChanged event is fired, but not the Loaded event.

Is there a way to force the Loaded event to fire, for instance, by re-initializing the view?

The reason why I need the Loaded event is that WPF f开发者_高级运维ires the selection change events on input controls during data binding and since I have logic that acts upon user-triggered selection change events, I need to be able to ignore those triggered by data binding. For now, the Loaded event seems to be the best option to do this. Escept for the described issue.

Thanks, Michael


Move whatever logic you have in the Loaded handler to the DataContextChanged handler if it needs to run every time the data context changes.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号