Click here to Skip to main content
15,943,419 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using WPF MVVM for a project. I have 8 View/ViewModel pairs that work well for the solution, but I have found myself duplicating two event handlers in code-behind for each View: OnLoaded and ExpandDetail (which is needed to respond to a request for more detail on a line in a DataGrid)

Moving them to the ViewModelBase (so each ViewModel would have the code) is not practical because they refer to WPF framework elements that in the View.

I believe they are rightly view oriented routines.

I get than old ugly feeling when having to repeat them in each view. Does anyone have advice about how I might get them into one, usable location?

What I have tried:

I have not tried it yet, but each view is a usercontrol, so I have thought about trying the idea of a ViewBase UserControl to base everything on but it seems kludgy.

I have searched the usual sources, with no results. I'm hoping someone has found a solution to this kind of thing that I can adapt
[no name] 8-Jun-22 0:07am    
Use a "static" class / method that accepts a view / user control / view model, etc. Instead of an (implicit) "this", you reference a variable / parameter (to the object in question). It seem like more code but it isn't; just better partitioning.
hardover 9-Jun-22 15:26pm    
This is a good recommendation. Thank you. It is squarely in the "should have thought of that" category.
I implemented it and it left me with only a one-line call for each event handler in the View code-behind. This allows the move to one instance of the common code which is now in the static class.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900