Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Controls - Should code behind be avoided at all costs?

Tags:

c#

wpf

.net-4.5

I have a WPF project and need to create a control that is specific to the domain but will be reused in multiple views.

The control must display a decimal value in 3 parts, the integral part and the decimal part split into 2 with different font sizes. I have a dependency property for the Amount and then split the amount in 3 parts in the code behind so I can show them in the specific labels. I also use the decimal amount to decide whether the amount is going up or down and subsequently change the background color of the control. All of this is done in the code behind. I know that some say that code behind is evil and I agree in most cases. However how would you implement this otherwise?

like image 881
Claudio Cauchi Avatar asked Jun 12 '15 14:06

Claudio Cauchi


1 Answers

No, it should not be avoided at all costs.

Remember, Data is Data, UI is UI.

For example, if you have code which does only UI stuff, then there is nothing wrong with having code behind.

Anything that works with actual data, including working with the ViewModel should generally be avoided in code-behind, as you would then be creating dependencies, which breaks the MVVM design pattern.

So to answer your question more directly, there isn't anything wrong with what you have done.

EDIT

Let me explain further.

Picture the scene, you have a View, with a button that needs to start a Storyboard when it has been clicked. (Of course, you can do this in XAML only, but this is just an example)

In this case, there is nothing wrong with adding a click event to the button and starting the storyboard from code-behind. This is UI only code, so it's safe.

However, let's say your button needs to change a property in your ViewModel when it is clicked. You should not get hold of the DataContext in the code-behind. You will need to use a Command because you need to keep the View separated from the ViewModel.

There's a stigma that if your views have code-behind, then you should be taken out back and shot in the back of the head, execution style. This is untrue.

All that said, MVVM is a pattern, not the law.

like image 96
Mike Eason Avatar answered Nov 19 '22 20:11

Mike Eason