WPF控件 - 应该在代码后面不惜一切代价避免? [英] WPF Controls - Should code behind be avoided at all costs?

查看:127
本文介绍了WPF控件 - 应该在代码后面不惜一切代价避免?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WPF项目,需要创建一个控制特定于域,但将在多个视图中重用。

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

该控件必须在3个部分展示一个十进制值,整数部分和小数部分分成2具有不同的字体大小。我有量的依赖属性,然后在3个部分的代码分割量的后面,所以我可以在特定标签显示它们。我还使用十进制量来决定的金额是否或上升下降以及随后改变控制的背景色。所有这一切都在后面的代码完成。我知道有些人说,后面的代码是邪恶的,我在大多数情况下达成一致。但是你会如何,否则实现这个?

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?

推荐答案

没有,它不应该在避免所有费用

No, it should not be avoided at all costs.

记住,数据是数据,用户界面​​是UI

例如,如果你有代码,做的 UI的东西,那么就没有什么错有后面的代码。

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

凡是与实际数据的作品,包括与视图模型一般应在后台代码来避免的工作,因为你会被创建依赖关系,这的的MVVM设计模式。

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.

修改

让我进一步解释。

照片的情景,你有一个观点,与需要启动一个故事板被点击时,它的按钮。 (当然,你只能在XAML做到这一点,但是这只是一个例子)

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)

在这种情况下,是没有错的添加click事件的按钮和启动从代码隐藏故事板。这就是 UI仅代码,因此它是安全的。

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.

但是,假设你的按钮需要更改属性您的视图模型被点击时它。您不该中得到的的DataContext 保持代码隐藏。您将需要使用命令,因为你需要保持在查看分开在视图模型

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.

所有这一切说,MVVM是一个模式,不是法律。

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

这篇关于WPF控件 - 应该在代码后面不惜一切代价避免?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆