星空雅梦

WPF教程(十五)MVVM框架

作者本人以前是做C++的,当然很顺利的进入到WinForm,这也让我基本没有View-Model思维。学习WPF说白点也是因为其强大的UI,其实我忽视了很重要的一点,直到接触了MVVM框架,其实Web前后端开发已经指明了未来编程趋势,各干各的:完美的前段和强劲的后端,个人是这么认为的。

WPF是微软视其为下一代用户界面技术,XAML的使用就是为了降低耦合度。那么我们不得不说说WinForm和WPF的区别了。

       1. WinForm更新UI的操作是通过后台操作UI名,即ID来完成的。WPF是通过数据Binding来实现UI更新的。
       2. WinForm响应用户操作的方式是事件Event。WPF是通过命令(Command)Binding的方式。

所以说,从你写的第一个WPF的Hello World!开始,你就要转变思路了!而不是很多人做的那种给按钮添加事件,点击触发然后抱怨和过去的Winform没啥区别,一点都不好用。

我们先看一个简单点的例子,不知道大家是不是一个有心的人,在之前的数据绑定过程中,我发现如果数据变化了呢?前台是否还会自主更新,答案是并不会,现在接触到MVVM,问题迎刃而解。

  1.  
    public class Name
  2.  
    {
  3.  
    string _userName;
  4.  
    string _companyName;
  5.  
    public string UserName
  6.  
    {
  7.  
    get { return _userName; }
  8.  
    set { _userName = value;}
  9.  
    }
  10.  
    public string CompanyName
  11.  
    {
  12.  
    get { return _companyName; }
  13.  
    set { _companyName = value;}
  14.  
    }
  15.  
    }
  16.  
    public partial class MainWindow : Window
  17.  
    {
  18.  
    Name MyName = new Name();
  19.  
    public MainWindow()
  20.  
    {
  21.  
    InitializeComponent();
  22.  
    MyName = base.DataContext as Name;
  23.  
    }
  24.  
    private void Update_Click(object sender, RoutedEventArgs e)
  25.  
    {
  26.  
    //界面不会更新
  27.  
    MyName.UserName = "Rose";
  28.  
    MyName.CompanyName= "中软易通";
  29.  
    }
  30.  
    }
  1.  
    <Window x:Class="mvvm.MainWindow"
  2.  
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.  
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.  
    xmlns:local="clr-namespace:mvvm"
  5.  
    Title="MainWindow" Height="147.806" Width="407.044">
  6.  
    <Window.DataContext>
  7.  
    <local:Name UserName="Pc-Yang" CompanyName="FS" />
  8.  
    </Window.DataContext>
  9.  
    <StackPanel VerticalAlignment="Center" Orientation="Horizontal">
  10.  
    <TextBlock Text="用户名:" Margin="20"/>
  11.  
    <TextBlock Text="{Binding UserName}" Margin="0,20"/>
  12.  
    <TextBlock Text="公司名称:" Margin="20"/>
  13.  
    <TextBlock Text="{Binding CompanyName}" Margin="0,20"/>
  14.  
    <Button Content="更新" Click="Update_Click" Margin="20"/>
  15.  
    </StackPanel>
  16.  
    </Window>

当我们点击按钮时候,根本没用啥反应,如果这种事情存在WPF中,不可能,否则就是失败。现在我们进行MVVM改造。定义一个NotificationBase类,这个类的作用是实现了INotifyPropertyChanged接口,目的是绑定数据属性。实现了它这个接口,数据属性发生变化后才会去通知UI,否则不会有任何。如果想在数据属性发生变化前知道,需要实现INotifyPropertyChanging接口。

  1.  
    public class Name : NotificationBase
  2.  
    {
  3.  
    string _userName;
  4.  
    string _companyName;
  5.  
    /// <summary>
  6.  
    /// 用户名
  7.  
    /// </summary>
  8.  
    public string UserName
  9.  
    {
  10.  
    get { return _userName; }
  11.  
    set { _userName = value; RaisePropertyChanged("UserName"); }
  12.  
    }
  13.  
    /// <summary>
  14.  
    /// 公司名
  15.  
    /// </summary>
  16.  
    public string CompanyName
  17.  
    {
  18.  
    get { return _companyName; }
  19.  
    set { _companyName = value; RaisePropertyChanged("CompanyName"); }
  20.  
    }
  21.  
    }
  22.  
    public class NotificationBase : INotifyPropertyChanged
  23.  
    {
  24.  
    public event PropertyChangedEventHandler PropertyChanged;
  25.  
    public void RaisePropertyChanged(string propertyName)
  26.  
    {
  27.  
    PropertyChangedEventHandler handler = PropertyChanged;
  28.  
    if (handler != null)
  29.  
    {
  30.  
    handler(this, new PropertyChangedEventArgs(propertyName));
  31.  
    }
  32.  
    }
  33.  
    }

整个逻辑不难理解,这里有个知识点就是接口实现事件,我在C#基础教程(三)做下知识点分析。我们也可以用命令来实现上面的MVVM,请看下面代码(这段代码感觉不是很走心,甚至有点累赘,可能MVVM的命令用法不是这样的)。

  1.  
    <Window x:Class="mvvm.MainWindow"
  2.  
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.  
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.  
    xmlns:local="clr-namespace:mvvm"
  5.  
    Title="MainWindow" Height="147.806" Width="407.044">
  6.  
    <Window.DataContext>
  7.  
    <local:Name UserName="Pc-Yang" CompanyName="FS" />
  8.  
    </Window.DataContext>
  9.  
    <StackPanel VerticalAlignment="Center" Orientation="Horizontal">
  10.  
    <TextBlock Text="用户名:" Margin="20"/>
  11.  
    <TextBlock Text="{Binding UserName}" Margin="0,20"/>
  12.  
    <TextBlock Text="公司名称:" Margin="20"/>
  13.  
    <TextBlock Text="{Binding CompanyName}" Margin="0,20"/>
  14.  
    <Button Command="{Binding PrintCmd}" Name="UpdateBtn" Content="更新" Click="Update_Click" Margin="20"/>
  15.  
    </StackPanel>
  16.  
    </Window>
  1.  
    public class Name : NotificationBase
  2.  
    {
  3.  
    string _userName;
  4.  
    string _companyName;
  5.  
    /// <summary>
  6.  
    /// 用户名
  7.  
    /// </summary>
  8.  
    public string UserName
  9.  
    {
  10.  
    get { return _userName; }
  11.  
    set { _userName = value; RaisePropertyChanged("UserName"); }
  12.  
    }
  13.  
    /// <summary>
  14.  
    /// 公司名
  15.  
    /// </summary>
  16.  
    public string CompanyName
  17.  
    {
  18.  
    get { return _companyName; }
  19.  
    set { _companyName = value; RaisePropertyChanged("CompanyName"); }
  20.  
    }
  21.  
    /// 方法函数
  22.  
    public void PrintNowName(object obj)
  23.  
    {
  24.  
    string[] Arr=obj as string[];
  25.  
    MainWindow.name.UserName = Arr[0];
  26.  
    MainWindow.name.CompanyName = Arr[1];
  27.  
    }
  28.  
    }
  29.  
    public class NotificationBase : INotifyPropertyChanged
  30.  
    {
  31.  
    //属性改变自动添加方法函数
  32.  
    public event PropertyChangedEventHandler PropertyChanged;
  33.  
    public void RaisePropertyChanged(string propertyName)
  34.  
    {
  35.  
    PropertyChangedEventHandler handler = PropertyChanged;
  36.  
    if (handler != null)
  37.  
    {
  38.  
    handler(this, new PropertyChangedEventArgs(propertyName));
  39.  
    }
  40.  
    }
  41.  
    }
  42.  
    class DelegateCommand : ICommand
  43.  
    {
  44.  
    public Action<object> ExecuteCommand = null;
  45.  
    public Func<object, bool> CanExecuteCommand = null;
  46.  
    public event EventHandler CanExecuteChanged;
  47.  
    //不停询问是否可以执行
  48.  
    public bool CanExecute(object parameter)
  49.  
    {
  50.  
    if (CanExecuteCommand != null)
  51.  
    {
  52.  
    return this.CanExecuteCommand(parameter);
  53.  
    }
  54.  
    else
  55.  
    {
  56.  
    return true;
  57.  
    }
  58.  
    }
  59.  
    //执行
  60.  
    public void Execute(object parameter)
  61.  
    {
  62.  
    if (this.ExecuteCommand != null) this.ExecuteCommand(parameter);
  63.  
    }
  64.  
    }
  65.  
    class ViewModel
  66.  
    {
  67.  
    public DelegateCommand PrintCmd { get; set; }
  68.  
    public Name name { get; set; }
  69.  
    public ViewModel()
  70.  
    {
  71.  
    this.name = new Name();
  72.  
    this.PrintCmd = new DelegateCommand();
  73.  
    this.PrintCmd.ExecuteCommand = new Action<object>(this.name.PrintNowName);
  74.  
    }
  75.  
    }
  76.  
    public partial class MainWindow : Window
  77.  
    {
  78.  
    static public Name name;
  79.  
    public MainWindow()
  80.  
    {
  81.  
    InitializeComponent();
  82.  
    //将上下文数据指向对象name
  83.  
    name = base.DataContext as Name;
  84.  
    }
  85.  
    private void Update_Click(object sender, RoutedEventArgs e)
  86.  
    {
  87.  
    //命令是否传递参数,即CanExecute的parameter
  88.  
    this.UpdateBtn.CommandParameter = new string[] { "jack", "鱼骨头" };
  89.  
    this.UpdateBtn.DataContext = new ViewModel();
  90.  
    }
  91.  
    }

总结

上下文数据DataContext对于属性Binding来说极为重要,关系能不能找到绑定属性。

DataContext是继承于顶层框架类的一个字段。

这里探讨的MVVM极为浅显,属于入门级,但为DataGrid等其它控件如何动态绑定,打下基础。

曾经因为项目接触到DevExpress控件,可以用其MVVM组件。

原文地址:https://www.cnblogs.com/LiZhongZhongY/p/10871749.html