簡體   English   中英

帶有擴展方法的WPF MVVM,沒有DataBinding! 為什么不?

[英]MVVM for WPF with extension methods, without DataBinding! Why not?

假設我有以下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可以是這個類,也可以包含它的一個實例(一個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");
  }
}

所以whiring不再是代碼背后,而是擴展方法。 MainWindow類的靜態字段的使用是最小的,因此可以跳過它。

xaml的外觀比使用DataBinding對象和花括號更自然。 我也遵循概念分離。 你怎么看 ?

你只是在做其他方式。

multiple ways of extending a classmultiple 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的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM