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,问题迎刃而解。

public class Name
{
    string _userName;
    string _companyName;     
    public string UserName
    {
        get { return _userName; }       
        set { _userName = value;}
    }   
    public string CompanyName
    {
        get { return _companyName; }
        set { _companyName = value;}         
    }
}
public partial class MainWindow : Window
{
    Name MyName = new Name();       
    public MainWindow()
    {
        InitializeComponent();
        MyName = base.DataContext as Name;                
    }
    private void Update_Click(object sender, RoutedEventArgs e)
    {
         //界面不会更新
        MyName.UserName = "Rose";
        MyName.CompanyName= "中软易通";
    }
}
<Window x:Class="mvvm.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:mvvm"
        Title="MainWindow"  Height="147.806" Width="407.044">
    <Window.DataContext>  
        <local:Name UserName="Pc-Yang" CompanyName="FS" />
    </Window.DataContext>
    <StackPanel VerticalAlignment="Center" Orientation="Horizontal">
        <TextBlock Text="用户名:" Margin="20"/>
        <TextBlock Text="{Binding UserName}" Margin="0,20"/>
        <TextBlock Text="公司名称:" Margin="20"/>
        <TextBlock Text="{Binding CompanyName}" Margin="0,20"/>
        <Button Content="更新" Click="Update_Click" Margin="20"/>
    </StackPanel>
</Window>

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

public class Name : NotificationBase
{
    string _userName;
    string _companyName;   
    /// <summary>
    /// 用户名
    /// </summary>
    public string UserName
    {
        get { return _userName; }
        set { _userName = value; RaisePropertyChanged("UserName"); }
    }
    /// <summary>
    /// 公司名
    /// </summary>
    public string CompanyName
    {
        get { return _companyName; }          
        set { _companyName = value; RaisePropertyChanged("CompanyName"); }
    }
}
public class NotificationBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    public void RaisePropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

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

<Window x:Class="mvvm.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:mvvm"
    Title="MainWindow"  Height="147.806" Width="407.044">
    <Window.DataContext>  
        <local:Name UserName="Pc-Yang" CompanyName="FS" />
    </Window.DataContext>
    <StackPanel VerticalAlignment="Center" Orientation="Horizontal">
        <TextBlock Text="用户名:" Margin="20"/>
        <TextBlock Text="{Binding UserName}" Margin="0,20"/>
        <TextBlock Text="公司名称:" Margin="20"/>
        <TextBlock Text="{Binding CompanyName}" Margin="0,20"/>
        <Button Command="{Binding PrintCmd}" Name="UpdateBtn" Content="更新" Click="Update_Click" Margin="20"/>
    </StackPanel>
</Window>
public class Name : NotificationBase
{
    string _userName;
    string _companyName;   
    /// <summary>
    /// 用户名
    /// </summary>
    public string UserName
    {
        get { return _userName; }
        set { _userName = value; RaisePropertyChanged("UserName"); }
    }
    /// <summary>
    /// 公司名
    /// </summary>
    public string CompanyName
    {
        get { return _companyName; }
        set { _companyName = value; RaisePropertyChanged("CompanyName"); }
    }
    /// 方法函数
    public void PrintNowName(object obj)
    {
        string[] Arr=obj as string[];
        MainWindow.name.UserName = Arr[0];
        MainWindow.name.CompanyName = Arr[1];
    }
}
public class NotificationBase : INotifyPropertyChanged
{
    //属性改变自动添加方法函数
    public event PropertyChangedEventHandler PropertyChanged;
    public void RaisePropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
class DelegateCommand : ICommand
{
    public Action<object> ExecuteCommand = null;
    public Func<object, bool> CanExecuteCommand = null;
    public event EventHandler CanExecuteChanged;
    //不停询问是否可以执行
    public bool CanExecute(object parameter)
    {
        if (CanExecuteCommand != null)
        {
            return this.CanExecuteCommand(parameter);
        }
        else
        {
            return true;
        }
    }
    //执行
    public void Execute(object parameter)
    {
        if (this.ExecuteCommand != null) this.ExecuteCommand(parameter);
    }
}
class ViewModel
{
    public DelegateCommand PrintCmd { get; set; }
    public Name name { get; set; }
    public ViewModel()
    {         
        this.name = new Name();        
        this.PrintCmd = new DelegateCommand();
        this.PrintCmd.ExecuteCommand = new Action<object>(this.name.PrintNowName);
    }
}
public partial class MainWindow : Window
{
    static public Name name;
    public MainWindow()
    {
        InitializeComponent();
        //将上下文数据指向对象name
        name = base.DataContext as Name;
    }
    private void Update_Click(object sender, RoutedEventArgs e)
    {
        //命令是否传递参数,即CanExecute的parameter
        this.UpdateBtn.CommandParameter = new string[] { "jack", "鱼骨头" };
        this.UpdateBtn.DataContext = new ViewModel();
    }
}

总结

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

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

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

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

  • 6
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,下面我将举一个简单的例子来介绍如何使用WPFMVVMLight搭建MVVM框架。 首先,我们需要安装MVVMLight NuGet包。打开Visual Studio,右键单击项目,选择“管理NuGet程序包”,搜索“MVVMLight”,点击“安装”。 接下来,我们创建一个Model类,它将包含我们需要绑定到UI的属性和方法。例如,我们创建一个名为“Person”的类,它有一个“Name”属性: ```csharp public class Person { private string _name; public string Name { get { return _name; } set { _name = value; } } } ``` 然后,我们创建一个ViewModel类,它将包含我们需要绑定到UI的命令和属性。ViewModel类需要继承MVVMLight的ViewModelBase类。例如,我们创建一个名为“MainViewModel”的类,它有一个“Person”属性和一个“UpdateCommand”命令: ```csharp public class MainViewModel : ViewModelBase { private Person _person; public Person Person { get { return _person; } set { _person = value; RaisePropertyChanged(() => Person); } } public RelayCommand UpdateCommand { get; private set; } public MainViewModel() { Person = new Person { Name = "John Doe" }; UpdateCommand = new RelayCommand(UpdatePerson); } private void UpdatePerson() { Person.Name = "Jane Doe"; } } ``` 最后,我们创建一个View类,它将绑定到ViewModel类的属性和命令。例如,我们创建一个名为“MainWindow”的窗口,它有一个文本框和一个按钮,用于更新Person的名称: ```xml <Window x:Class="MVVMExample.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:vm="clr-namespace:MVVMExample" Title="MainWindow" Height="350" Width="525"> <Window.DataContext> <vm:MainViewModel/> </Window.DataContext> <Grid> <TextBox Text="{Binding Person.Name}"/> <Button Content="Update" Command="{Binding UpdateCommand}"/> </Grid> </Window> ``` 现在,我们已经完成了MVVM框架的搭建。当我们启动应用程序时,将显示一个窗口,其中包含一个文本框和一个按钮。当单击按钮时,Person的名称将更新为“Jane Doe”。 希望这个例子能够帮助你了解如何使用WPFMVVMLight搭建MVVM框架。如果你有任何疑问,请随时问我。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值