Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
488 views
Welcome To Ask or Share your Answers For Others

1 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...