使用WPF開發應用程序,MVVM也許是個繞不過去的東西了,做一個小程序,做個參考。
MVVM是Model-View-ViewModel的簡寫,代碼分離真是做的相當到位,通過界面和控制類中的數據綁定,來實現數據的展示。
第一步,建立view和viewmodel的聯系。
1.新建WPF應用程序。
2.添加viewmodel文件夾,新建一個viewmodel的類,初始化的時候,實例化主窗口。
MainWindow Mw = new MainWindow();
3.修改app.xaml中項目的啟動方式,使用startup事件,實例化viewmodel。
MainWindowViewModel Mw = new MainWindowViewModel();
第二步,view的數據綁定。
1.viewmodel中添加屬性,然后設置view的數據上下文,最后,顯示view。
public string Name { get; set; }
Name = "hello MVVM";
Mw.DataContext = this;
Mw.ShowDialog();
2.view中要做的就是綁定這個屬性,添加一個按鈕,content綁定name屬性即可。
Button Content="{Binding Name}"
這只是一個最簡單的展示,數據實體應該存放在model中,這個例子中暫時還沒有用到model。
view的代碼:

<Window x:Class="MyWPFApp.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"> <Grid> <Button Content="{Binding Name}" Height="23" HorizontalAlignment="Left" Margin="116,53,0,0" Name="button1" VerticalAlignment="Top" Width="75" /> </Grid> </Window>
viewmodel的代碼:

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MyWPFApp.ViewModel { class MainWindowViewModel { public MainWindowViewModel() { Initialize(); } /// <summary> /// 初始化 /// </summary> private void Initialize() { MainWindow Mw = new MainWindow(); Name = "hello MVVM"; Mw.DataContext = this; Mw.ShowDialog(); } #region 屬性 public string Name { get; set; } #endregion } }
app.xaml的代碼:

<Application x:Class="MyWPFApp.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Startup="Application_Startup"> <Application.Resources> </Application.Resources> </Application>
app.xaml.cs的代碼:

using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Windows; using MyWPFApp.ViewModel; namespace MyWPFApp { /// <summary> /// App.xaml 的交互邏輯 /// </summary> public partial class App : Application { private void Application_Startup(object sender, StartupEventArgs e) { MainWindowViewModel Mw = new MainWindowViewModel(); } } }
主界面的cs文件中沒有添加一行代碼,在MVVM模式中,界面要做的只有一個數據的綁定,理論上,界面是相對獨立的。
當然,MVVM的綁定並沒有這么簡單,事件綁定的實現,我以后也會嘗試着寫寫看,理解原理很重要,但是,入門的操作同樣也很重要,一步一步來,慢慢的去深入。。。