WPF 编程方法论
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14381402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF Programming Methodology
提问by SigmaOmega
In my APP I'm using an API of a software that my tool is managing. I've DAL that contain 16 classes, 3 of them are singletons. I've some logic in the .csfiles and XAML's off course.
在我的应用程序中,我正在使用我的工具正在管理的软件的 API。我有包含 16 个类的 DAL,其中 3 个是单例。我在.cs文件中有一些逻辑,XAML当然了。
My question is, I see a lot of comments that an app written in WPF should use MVVM, and this will make the code more usable and readable, can I transform my code to be MVVM? what it the actual meaning of MVVM (not Wikipedia or manual definition)?
我的问题是,我看到很多评论说用 WPF 编写的应用程序应该使用 MVVM,这将使代码更具可用性和可读性,我可以将我的代码转换为 MVVM 吗?MVVM 的实际含义是什么(不是维基百科或手动定义)?
I also use SQL queries and I read a paper about EF (Entity Framework), can MVVM and EF coexist together in the same project?
我也使用 SQL 查询,我阅读了一篇关于 EF(实体框架)的论文,MVVM 和 EF 可以在同一个项目中共存吗?
回答by Federico Berasategui
The actual meaning of MVVM is: UI is not Data. Data is Data, UI is UI.
MVVM的实际含义是:UI不是Data。数据就是数据,用户界面就是用户界面。
This means that you should not develop the application in a way that the program logic (often called business logic) is tightly coupled or dependent on the state of UI components, but instead make it dependent on the state of data items (be it the Model, or the View Model).
这意味着您不应该以程序逻辑(通常称为业务逻辑)紧密耦合或依赖于 UI 组件状态的方式开发应用程序,而应使其依赖于数据项的状态(无论是模型,或视图模型)。
For example, in other frameworks (such as winforms), if you have a screen that contains a textbox, and a button, you usually add a click event handler to the button and then read the text from the textbox. in MVVM, the Text property of the TextBox should be bound to a string property in the ViewModel, and the button should be bound to a Command in the ViewModel as well.
例如,在其他框架(如 winforms)中,如果您有一个包含文本框和按钮的屏幕,通常会向按钮添加一个单击事件处理程序,然后从文本框中读取文本。在 MVVM 中,TextBox 的 Text 属性应该绑定到 ViewModel 中的 string 属性,按钮也应该绑定到 ViewModel 中的 Command。
This allows for an abstraction of the UI (which is the ViewModel), so that, as I said before, your application logic can be dependent on not the UI but an abstraction of it.
这允许对 UI(即 ViewModel)进行抽象,因此,正如我之前所说,您的应用程序逻辑可以不依赖于 UI,而是依赖于它的抽象。
This allows for a huge amount of scalability in the UI and the logic, and also allows for the testability of several aspects of UI behavior because a big portion of the UI behavior is defined in the ViewModel.
这允许 UI 和逻辑中的大量可伸缩性,并且还允许 UI 行为的多个方面的可测试性,因为 UI 行为的很大一部分是在 ViewModel 中定义的。
There are other aspects of MVVM as well, but the main realization is that.
MVVM 也有其他方面,但主要的实现就是这样。
Edit:
编辑:
I will add a concrete example of this for completeness of the answer:
为了答案的完整性,我将添加一个具体的例子:
1 - Non MVVM WPF:
1 - 非 MVVM WPF:
XAML:
XAML:
<StackPanel>
<TextBox x:Name="txtLastName"/>
<Button Content="Click Me" Click="Button_Click"/>
</StackPanel>
Code behind:
后面的代码:
private void Button_Click(object sender, EventArgs e)
{
//Assuming this is the code behind the window that contains the above XAML.
var lastname = this.txtLastName.Text;
//Here you do some actions with the data obtained from the textbox
}
2 - MVVM WPF:
2 - MVVM WPF:
XAML:
XAML:
<StackPanel>
<StackPanel.DataContext>
<my:MyViewModel/>
</StackPanel.DataContext>
<TextBox Text="{Binding LastName}"/>
<Button Content="Click Me" Command="{Binding MyCommand}"/>
</StackPanel>
ViewModel:
视图模型:
public class MyViewModel
{
public string LastName { get; set; }
public Command MyCommand { get; set; }
public MyViewModel()
{
// The command receives an action on the constructor,
// which is the action to execute when the command is invoked.
MyCommand = new Command(ExecuteMyCommand);
}
private void ExecuteMyCommand()
{
//Only for illustration purposes, not really needed.
var lastname = this.LastName;
//Here you do some actions with the data obtained from the textbox
}
}
As you can see in the above example, the ViewModel contains no reference at all to the View. Thus, the View could be anything, as long as the {Bindings}are kept in place.
正如您在上面的示例中看到的,ViewModel 根本不包含对 View 的引用。因此,只要{Bindings}保持原位,View 可以是任何东西。
The glue that magically makes them work together is the DataContextProperty of WPF UI Elements, which is the object that all bindings will be resolved against.
神奇地让它们一起工作的DataContext粘合剂是 WPF UI 元素的属性,它是所有绑定将针对的对象。
There are other things, such as the Property Change Notification in the ViewModel to enable two-way bindings, but that is out of the scope of this answer.
还有其他东西,例如 ViewModel 中的属性更改通知以启用双向绑定,但这超出了本答案的范围。
Also keep in mind that MVVM is a design pattern, whereas WPF is a framework. MVVM is also being currently applied in other technologies (there is currently a lot of buzz about MVVM for the web, with JavaScript and stuff like that)
还要记住,MVVM 是一种设计模式,而 WPF 是一种框架。MVVM 目前也被应用在其他技术中(目前有很多关于 MVVM 用于网络的讨论,使用 JavaScript 和类似的东西)
I suggest you read the books mentioned in other answers as well as this Tutorialfor more WPF-specific aspects.
我建议您阅读其他答案中提到的书籍以及本教程,以了解更多 WPF 特定方面的信息。
回答by Big Daddy
My question is, I see a lot of comments that an app written in WPF should use MVVM, and this will make the code more usable and readable, can I transform my code to be MVVM?
我的问题是,我看到很多评论说用 WPF 编写的应用程序应该使用 MVVM,这将使代码更具可用性和可读性,我可以将我的代码转换为 MVVM 吗?
There's no requirement that you need to use the MVVM pattern - none. You need to consider the complexity of the app you are building and the development groups skill-set. Generally speaking, if it's a small or small/medium app then MVVM maybe over-engineering. If the group's skills/talent aren't a good fit for a separated presentation pattern, then MVVM may not be a good decision.
没有要求您需要使用 MVVM 模式 - 没有。您需要考虑正在构建的应用程序的复杂性以及开发团队的技能组合。一般来说,如果它是一个小型或中小型应用程序,那么 MVVM可能会过度设计。如果团队的技能/才能不适合单独的演示模式,那么 MVVM 可能不是一个好的决定。
If done right, then MVVM gives you all the sorts of benefits that you've read about. Conversely, if it's done wrong, then it can be a development and maintanence nightmare - definitely not more readable and usable. From personal experience, I think it's easier to work on a poorly written code-behind app rather than a poorly written MVVM based one.
如果做得好,那么 MVVM 将为您提供您所了解的各种好处。相反,如果它做错了,那么它可能是开发和维护的噩梦——绝对不是更具可读性和可用性。从个人经验来看,我认为在编写糟糕的代码隐藏应用程序上比编写基于 MVVM 的应用程序更容易。
Sure, you can rewrite your current app to the MVVM pattern. Just remove your code-behind and put it into your view-models, helper classes, repository classes, biz-logic classes, etc. Don't fall into the trap of putting everything into you view-models, creating an MVVM-glorified code-behind.
当然,您可以将当前的应用程序重写为 MVVM 模式。只需删除您的代码隐藏并将其放入您的视图模型、帮助程序类、存储库类、业务逻辑类等中。不要陷入将所有内容放入您的视图模型中的陷阱,创建一个 MVVM 美化的代码-在后面。
I also use SQL queries and I read a paper about EF (Entity Framework), can MVVM and EF leave together in the same project?
我也使用 SQL 查询,我阅读了一篇关于 EF(实体框架)的论文,MVVM 和 EF 可以放在同一个项目中吗?
Sure, they can. Just remember that EF is a data access technology and MVVM is a design pattern. You'll probably use EF in your DAL classes that you mention.
当然,他们可以。请记住,EF 是一种数据访问技术,而 MVVM 是一种设计模式。您可能会在您提到的 DAL 类中使用 EF。
One final thought, if you decide to go down the MVVM route then you should consider using a framework that facilitates it, like Prism. Oh, and be prepared for quite a bit of learning and frustration.
最后一个想法,如果你决定走 MVVM 路线,那么你应该考虑使用一个促进它的框架,比如Prism. 哦,准备好接受相当多的学习和挫折。
回答by Dr. ABT
I would definitely look into DependencyInjection, using a framework like Unity.
我肯定会使用像Unity这样的框架来研究DependencyInjection。
Your Singleton classes could be registered with a DependencyInjection container and injected into constructors of other classes (such as ViewModels). So could other DAL classes which need to be instantiated regularly and injected into classes.
您的 Singleton 类可以注册到 DependencyInjection 容器中,并注入到其他类(例如 ViewModels)的构造函数中。其他需要定期实例化并注入到类中的 DAL 类也是如此。
DependencyInjection is the single most important design pattern when developing large enterprise software applications and is applicable for both Client & Server code. MVVM is a nice pattern but won't address the issue of overall application complexity related to dependency coupling.
DependencyInjection 是开发大型企业软件应用程序时最重要的单一设计模式,适用于客户端和服务器代码。MVVM 是一种不错的模式,但不会解决与依赖耦合相关的整体应用程序复杂性问题。
回答by Dhru 'soni
These are mine specific to MVVM
这些是我特定于 MVVM 的
1) Increases the "Blendability"of your views (ability to use Expression Blend to design views). This enables a separation of responsibilities on teams that are lucky enough to have a designer and a programmer... each can work independent of the other.
1) 增加视图的“可混合性”(使用 Expression Blend 设计视图的能力)。这使得有幸拥有设计师和程序员的团队的职责分离......每个人都可以独立工作。
2) "Lookless"view logic. Views are agnostic from the code that runs behind them, enabling the same view logic to be reused across multiple views or have a view easily retooled or replaced. Seperates concerns between "behavior" and "style".
2)“Lookless”视图逻辑。视图与运行在它们后面的代码无关,使相同的视图逻辑可以在多个视图中重用,或者可以轻松地重新组装或替换视图。分离“行为”和“风格”之间的关注点。
3) No duplicated code to update views.In code-behind you will see a lot of calls to "myLabel.Text = newValue" sprinkled everywhere. With MVVM you can be assured the view is updated appropriately just by setting the underlying property and all view side-effects thereof.
3)没有重复的代码来更新视图。在代码隐藏中,您会看到大量对“myLabel.Text = newValue”的调用随处可见。使用 MVVM,您可以确保仅通过设置底层属性及其所有视图副作用来适当地更新视图。
4) Testability.Since your logic is completely agnostic of your view (no "myLabel.Text" references), unit testing is made easy. You can test the behavior of a ViewModel without involving its view. This also enabled test-driven development of view behavior, which is almost impossible using code-behind.
4)可测试性。由于您的逻辑与您的视图完全无关(没有“myLabel.Text”引用),因此单元测试变得容易。您可以在不涉及其视图的情况下测试 ViewModel 的行为。这也实现了视图行为的测试驱动开发,这几乎不可能使用代码隐藏。
The other two patterns are really sort of separate in terms of the concerns they address. You can use MVVM with MVP and MVC (most good samples out there do some form of this).
就它们所解决的问题而言,其他两种模式确实有些不同。您可以将 MVVM 与 MVP 和 MVC 结合使用(大多数优秀的示例都采用了某种形式)。
In fact, MVP (w/ a Passive View, rather than a Supervising Controller) is really just a variant of MVVM, in my opinion.
事实上,在我看来,MVP(带有被动视图,而不是监督控制器)实际上只是 MVVM 的一个变体。

