WPF 一个MVVM的简单例子

简介:

如下图是系统的结构图:这个示例是模仿计算器的MVVM模式的精简版,非常简单。

这篇文章就开门见山了,有关MVVM的理论部分,请参考MVVM设计模式

1、App中的代码:

public  App()
{
     CalculatorView view = new  CalculatorView();
     view.DataContext = new  CalculatorViewModel();
     view.Show();
}

2、Model层中CauculatorModel的代码

class  CauculatorModel
{
      public  string  FirstOperand { get ; set ; }
      public  string  SecondOperand { get ; set ; }
      public  string  Operation { get ; set ; }
      public  string  Result { get ; set ; }
}

3、Command

public  class  DeletgateCommand<T>:ICommand
  {
      private  readonly  Action<T> _executeMethod = null ;
      private  readonly  Func<T, bool > _canExecuteMethod = null ;
 
      public  DeletgateCommand(Action<T> executeMethod)
          : this (executeMethod, null )
      { }
 
      public  DeletgateCommand(Action<T> executeMethod, Func<T, bool > canExecuteMethod) 
      {
          if  (executeMethod == null )
              throw  new  ArgumentNullException( "executeMetnod" );
          _executeMethod = executeMethod;
          _canExecuteMethod = canExecuteMethod;
      }
 
      #region ICommand 成员
      /// <summary>
      ///  Method to determine if the command can be executed
      /// </summary>
      public  bool  CanExecute(T parameter)
      {
          if  (_canExecuteMethod != null )
          {
              return  _canExecuteMethod(parameter);
          }
          return  true ;
 
      }
 
      /// <summary>
      ///  Execution of the command
      /// </summary>
      public  void  Execute(T parameter)
      {
          if  (_executeMethod != null )
          {
              _executeMethod(parameter);
          }
      }
 
      #endregion
 
 
      event  EventHandler ICommand.CanExecuteChanged
      {
          add { CommandManager.RequerySuggested += value; }
          remove { CommandManager.RequerySuggested -= value; }
      }
 
      #region ICommand 成员
 
      public  bool  CanExecute( object  parameter)
      {
          if  (parameter == null  && typeof (T).IsValueType)
          {
              return  (_canExecuteMethod == null );
 
          }
          
          return  CanExecute((T)parameter);
      }
 
      public  void  Execute( object  parameter)
      {
          Execute((T)parameter);
      }
 
      #endregion
  }

 

4、ViewModwl层,为了简化,此处Add方法采用硬编码的形式

public  class  CalculatorViewModel
  {
      CauculatorModel calculatorModel;
      private  DeletgateCommand< string > addCommand;
      
 
      public  CalculatorViewModel()
      {
          calculatorModel = new  CauculatorModel();
      }
 
      #region Public Properties
      public  string  FirstOperand
      {
          get  return  calculatorModel.FirstOperand;  }
          set  { calculatorModel.FirstOperand = value;  }
      }
      public  string  SecondOperand
      {
          get  { return  calculatorModel.SecondOperand; }
          set  { calculatorModel.SecondOperand = value; }
      }
      public  string  Operation
      {
          get  { return  calculatorModel.Operation; }
          set  { calculatorModel.Operation = value; }
      }
      public  string  Result
      {
          get  { return  calculatorModel.Result; }
          set  { calculatorModel.Result = value; }
      }
      #endregion
 
      public  ICommand AddCommand
      {
          get
          {
              if  (addCommand == null )
              {
                  addCommand = new  DeletgateCommand< string >(Add, CanAdd);
              }
              return  addCommand;
 
          }
      }
         
      public   void  Add( string  x)
      {
          FirstOperand = x;
          SecondOperand = x;
          Result = ( double .Parse(FirstOperand) + double .Parse(SecondOperand)).ToString();
          Operation = "+" ;
          MessageBox.Show( FirstOperand+ Operation +SecondOperand + "="  + Result);
      }
 
      private  static  bool  CanAdd( string  num)
      {
          return  true ;
      }
  }

 

ViewModelBase中的代码:

public  abstract  class  ViewModelBase : INotifyPropertyChanged
  {
      public  event  PropertyChangedEventHandler PropertyChanged;
 
      protected  void  OnPropertyChanged( string  propertyName)
      {
          PropertyChangedEventHandler handler = PropertyChanged;
 
          if  (handler != null )
          {
              handler( this , new  PropertyChangedEventArgs(propertyName));
          }
      }
 
  }

 5、View层

<Grid>   
        <TextBox  Height= "23"  Margin= "12,63,0,0"  Name= "textBox1"  VerticalAlignment= "Top"  HorizontalAlignment= "Left"   Width= "120"  />
        <Label Margin= "12,25,95,0"  Name= "label2"  Height= "32"  VerticalAlignment= "Top" >请输入x的值! x+x=? </Label>
        <Button Height= "23"  Command= "{Binding AddCommand}"  
                CommandParameter= "{Binding ElementName=textBox1,Path=Text}"    HorizontalAlignment= "Left"  Margin= "12,102,0,0"  Name= "button1"  VerticalAlignment= "Top"  Width= "75" >
            确定</Button>
    </Grid>

 CommandParameter里传递的是一个参数,当然可以传递多个参数。

6、效果图:

参考资料:MVVM的一个Example

 


本文转自Work Hard Work Smart博客园博客,原文链接:http://www.cnblogs.com/linlf03/archive/2011/09/11/2173833.html,如需转载请自行联系原作者

目录
相关文章
|
前端开发 C# 开发者
WPF开发者必读:MVVM模式实战,轻松构建可维护的应用程序,让你的代码更上一层楼!
【8月更文挑战第31天】在WPF应用程序开发中,MVVM(Model-View-ViewModel)模式通过分离关注点,提高了代码的可维护性和可扩展性。本文详细介绍了MVVM模式的三个核心组件:Model(数据模型)、View(用户界面)和ViewModel(处理数据绑定与逻辑),并通过示例代码展示了如何在WPF项目中实现MVVM模式。通过这种模式,开发者可以更高效地构建桌面应用程序。希望本文能帮助你在WPF开发中更好地应用MVVM模式。
651 1
|
12月前
|
设计模式 前端开发 C#
WPF 项目中 MVVM模式 的简单例子说明
本文通过WPF项目中的加法操作示例,讲解了MVVM模式的结构和实现方法,包括数据模型、视图、视图模型的创建和数据绑定,以及命令的实现和事件通知机制。
|
前端开发 C# 设计模式
“深度剖析WPF开发中的设计模式应用:以MVVM为核心,手把手教你重构代码结构,实现软件工程的最佳实践与高效协作”
【8月更文挑战第31天】设计模式是在软件工程中解决常见问题的成熟方案。在WPF开发中,合理应用如MVC、MVVM及工厂模式等能显著提升代码质量和可维护性。本文通过具体案例,详细解析了这些模式的实际应用,特别是MVVM模式如何通过分离UI逻辑与业务逻辑,实现视图与模型的松耦合,从而优化代码结构并提高开发效率。通过示例代码展示了从模型定义、视图模型管理到视图展示的全过程,帮助读者更好地理解并应用这些模式。
348 0
|
前端开发 开发者 C#
WPF开发者必读:MVVM模式实战,轻松实现现代桌面应用架构,让你的代码更上一层楼!
【8月更文挑战第31天】在WPF应用程序开发中,MVVM(Model-View-ViewModel)模式通过分离应用程序的逻辑和界面,提高了代码的可维护性和可扩展性。本文介绍了MVVM模式的三个核心组件:Model(数据模型)、View(用户界面)和ViewModel(处理数据绑定和逻辑),并通过示例代码展示了如何在WPF项目中实现MVVM模式。通过这种方式,开发者可以构建更加高效和可扩展的桌面应用程序。
654 0
|
设计模式 前端开发 C#
WPF/C#:理解与实现WPF中的MVVM模式
WPF/C#:理解与实现WPF中的MVVM模式
1017 0
|
前端开发 C# 图形学
【.NET6+WPF】WPF使用prism框架+Unity IOC容器实现MVVM双向绑定和依赖注入
前言:在C/S架构上,WPF无疑已经是“桌面一霸”了。在.NET生态环境中,很多小伙伴还在使用Winform开发C/S架构的桌面应用。但是WPF也有很多年的历史了,并且基于MVVM的开发模式,受到了很多开发者的喜爱。
947 0
【.NET6+WPF】WPF使用prism框架+Unity IOC容器实现MVVM双向绑定和依赖注入
|
设计模式 开发框架 前端开发
深入理解WPF中MVVM的设计思想
近些年来,随着WPF在生产,制造,工业控制等领域应用越来越广发,很多企业对WPF开发的需求也逐渐增多,使得很多人看到潜在机会,不断从Web,WinForm开发转向了WPF开发,但是WPF开发也有很多新的概念及设计思想,如:数据驱动,数据绑定,依赖属性,命令,控件模板,数据模板,MVVM等,与传统WinForm,ASP.NET WebForm开发,有很大的差异,今天就以一个简单的小例子,简述WPF开发中MVVM设计思想及应用。
263 0
|
前端开发
WPF-Binding问题-MVVM中IsChecked属性CommandParameter转换值类型空异常
WPF-Binding问题-MVVM中IsChecked属性CommandParameter转换值类型空异常
278 0
|
前端开发 算法 JavaScript
走进WPF之MVVM完整案例
走进WPF之MVVM完整案例
475 0
|
前端开发 C# 数据库
WPF MVVM系统入门-下
本文详细讲解WPF,MVVM开发,实现UI与逻辑的解耦。
416 0