将代码保留在XAML代码后面的真正好处是什么? [英] What is the real advantage of keeping code out of the XAML code behind?

查看:89
本文介绍了将代码保留在XAML代码后面的真正好处是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Silverlight社区付出了很多努力,以使XAML的代码尽可能不包含在文件后.这背后的真正动机是什么?

There is a lot of effort in the Silverlight community to keep a XAML's code behind file as free of code as possible. What is the real motivation behind this?

例如,使用命令而不是事件处理程序有什么优势?如果我有

For example, what is the advantage of using a command instead of an event handler? If I have

<Button x:Name="SaveButton" Content="Save" Click="SaveButton_Click" />

...

private void SaveButton_Click(object sender, RoutedEventArgs e) {
    _myViewModel.SaveChanges();
}

那为什么要这样呢?

<Button x:Name="SaveButton" Content="Save" Command="{Binding SaveCommand}" />

显然,在我的视图模型中,SaveCommand将有效地调用SaveChanges().

Where obviously the SaveCommand in my view model is effectively going to invoke SaveChanges().

这可能导致视图为100%XAML的情况,甚至在XAML中实例化视图模型,并且视图和视图模型之间的连接完全通过绑定来完成.当然很干净,但是还有什么呢?灵活的?为什么?该视图仍然需要使用适当的ViewModel,因此如果两者之间的连接存在并且是隐式的,为什么不使其更加明确?它还具有丢失编译时间支持的缺点.如果我将按钮连接到一个不存在的事件处理程序,则编译器会告诉我.如果绑定到不存在的命令,则不会.

This can lead to situations where the view is 100% XAML, even instantiating the view model in XAML, and the connections between the view and view model are completely done through binding. Sure it's clean, but what else is it? Flexible? Why? the view still needs to work with the proper ViewModel, so if the connection between the two exists and is implicit, why not make it more explicit? It also has the disadvantage of losing compile time support. If I hook my button up to an event handler that doesn't exist, the compiler will tell me. It won't if I bind to a non-existent command.

推荐答案

它使单元测试和/或TDD更加容易.通过使用MVVM和命令,我可以实质上构建我的视图模型和命令TDD样式,并测试大多数视图逻辑,而实际上根本没有XAML视图.

It makes unit testing and / or TDD easier. By using MVVM and commanding, I can essentially build my view model and commands TDD style and have most of the view logic tested without actually having the XAML view at all.

这篇关于将代码保留在XAML代码后面的真正好处是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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