0

假设我有以下 XAML :

<Window x:Class="Test.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">

<Canvas>
    <Button Content="Write something" Canvas.Left="43" Canvas.Top="159" Width="162" Height="42" Click="Button_Click_1"/>
</Canvas>

我的 ViewModel 可以是此类,也可以包含它的实例(视图模型逻辑):

 //Here is my static class for extension methods
 public static  class ExtendenWindowClass
{

  /// <summary>
  /// Eventhandler for Button
  /// </summary>
  /// <param name="obj"></param>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  public static void Button_Click_1(this MainWindow obj, object sender, RoutedEventArgs e)
  {

      MessageBox.Show("Wait 10 seconds");
      Thread.Sleep(10000);
      MessageBox.Show("Ready, now you can press again");
  }
}

因此,嗡嗡声不再在代码后面,而是在扩展方法中。MainWindow 类的静态字段的使用很少,因此可以跳过。

xaml 的外观比 DataBinding 对象和花括号更自然。而且我也遵循概念分离。你怎么看 ?

4

1 回答 1

2

你只是在做相反的事情。

multiple ways of extending a class。其中两个是——

  1. 部分课。
  2. 扩展方法。

code behind您使用partial class实现扩展您的类时。

public partial class MainWindow : Window { }

在您发布的代码中,您正在使用其他方式(即扩展方法)实现这一目标。我不认为这样你会在这里得到更多的东西。


MVVM 模式的主要动机是decouple UI logic from business logic. 也不能在扩展方法中或在代码后面有代码unit tested。代码后面和窗口上的扩展方法对我来说是完全一样的。你View and ViewModel should work oblivious to each other这样它就可以由不同的开发人员同时进行。

你可以在这里这里阅读更多关于 MVVM 的信息。

于 2013-11-10T12:35:43.237 回答