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

查看:13
本文介绍了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?

推荐答案

不,不应该不惜一切代价避免它.

记住,数据就是数据,用户界面就是用户界面.

例如,如果您的代码处理 UI 内容,那么将代码隐藏起来并没有错.

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

任何处理实际数据的事情,包括处理 ViewModel 通常应该避免在代码隐藏中,因为你会创建依赖项,这会破坏 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.

编辑

让我进一步解释.

想象一下场景,你有一个视图,有一个按钮,当它被点击时需要启动一个Storyboard.(当然,您只能在 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)

在这种情况下,向按钮添加点击事件并从代码隐藏开始故事板没有任何问题.这是仅限用户界面的代码,因此很安全.

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.

但是,假设您的按钮需要在点击时更改 ViewModel 中的属性.您不应该在代码隐藏中获取DataContext.您将需要使用 Command,因为您需要将 ViewViewModel 分开.

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天全站免登陆