views:

117

answers:

2

Hi,

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.

+4  A: 

I think the most elegant solution to this problem is probably to ignore it.

The existence of code-behind files in your project costs you next to nothing. And coming up with some special scheme to make them go away just creates something that you have to document and manage. (And figure out how to disable, when the day comes when you do need a code-behind file for a user control. Because sooner or later you will - for instance, you can't implement drag and drop in your view model.)

Why would you do this to yourself?

Robert Rossney
+1  A: 

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.

SondreB