Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
498 views
in Technique[技术] by (71.8m points)

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

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...