I am coding a WPF application using MVVM pattern. I don’t need to have codebehind files for my user controls. What is the best way to remove these files elegantly?
I can create a user control class then I can use this class for my all views. (for more info: http://sondreb.com/blog/post/No-Code-Behind-for-MVVM.aspx)
Are there any alternative ways?
Thank you.
I don’t think you can avoid not using reflection to call the InitializeComponent (to answer your question about alternative ways). Avoiding code-behind has benefits and drawbacks, one of the benefits I see is that double-clicking on any controls no longer works, neither in Blend nor Visual Studio. This “forces” me to never make a “quick-fix” for certain actions.
On the other hand, doing “quick-fix” to verify something becomes tougher, so it’s a trade-of you have to decide upon.
There is little wrong having the code-behind laying around, in one of my current big projects I have no code-behind for approx. 20% of the XALM files, in the rest I just haven’t removed them (yet).
You can implement drag and drop without relying on code-behind logic, I’ve done it with my Silverlight 4 project which required handling some actions when running out-of-browser without the window border.
Depending on your MVVM-implementation and framework, you can access the view from your View Model. While this should be avoided if possible, sometimes it’s just not a viable solution. Caliburn.Micro for instance, gives you a clean way to access the view by implementing the IViewAware interface and calling the GetView method.