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

1.1k views Asked by At

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?

2

There are 2 answers

3
Mike Eason On BEST ANSWER

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.

1
Noman Khan On

Instead of splitting Amount in 3 in Code Behind, You can keep one Property Amount in ViewModel and Use a Converter with 3 Parameters to extract one of the three pieces of information for Display. So you can have 3 bindings like this:

"{Binding Amount, Mode=TwoWay, Converter={StaticResource AmountSplitterConverter},ConverterParameter=Integral}"

"{Binding Amount, Mode=TwoWay, Converter={StaticResource AmountSplitterConverter},ConverterParameter=Decimal1}"

"{Binding Amount, Mode=TwoWay, Converter={StaticResource AmountSplitterConverter},ConverterParameter=Decimal2}"

Let me know if you need any further help in implementing it or if it's not clear.