WPF MVVM设计模式的ViewModelBase和CommandBase代码



ViewModelBase和CommandBase代码的整理如下:

 

1.ViewModelBase.cs

[c-sharp] view plain copy print ?
  1. using System;  
  2. using System.ComponentModel;  
  3. using System.Linq.Expressions;  
  4. /// <summary>  
  5. /// WPF MVVC设计模式ViewMode基本功能类  
  6. /// </summary>  
  7. public abstract class ViewModelBase : INotifyPropertyChanged, IDisposable  
  8. {  
  9.     #region Public Properties  
  10.     /// <summary>  
  11.     /// 显示名称  
  12.     /// </summary>  
  13.     public virtual string DisplayName { getprotected set; }  
  14.     #endregion  
  15.     #region Constructor  
  16.     /// <summary>  
  17.     /// 实例化一个ViewModelBase对象  
  18.     /// </summary>  
  19.     protected ViewModelBase()  
  20.     {  
  21.     }  
  22.     #endregion  
  23.     #region INotifyPropertyChanged Members  
  24.     /// <summary>  
  25.     /// 触发属性发生变更事件  
  26.     /// </summary>  
  27.     /// <typeparam name="T">泛型标记,会匹配函数返回类型,不必手动填写</typeparam>  
  28.     /// <param name="action">以函数表达式方式传入属性名称,表达式如下即可:()=>YourViewModelProperty</param>  
  29.     protected void OnPropertyChanged<T>(Expression<Func<T>> action)  
  30.     {  
  31.         var propertyName = GetPropertyName(action);  
  32.         OnPropertyChanged(propertyName);  
  33.     }  
  34.     private static string GetPropertyName<T>(Expression<Func<T>> action)  
  35.     {  
  36.         var expression = (MemberExpression)action.Body;  
  37.         var propertyName = expression.Member.Name;  
  38.         return propertyName;  
  39.     }  
  40.     private void OnPropertyChanged(string propertyName)  
  41.     {  
  42.         PropertyChangedEventHandler handler = PropertyChanged;  
  43.         if (handler != null)  
  44.         {  
  45.             var e = new PropertyChangedEventArgs(propertyName);  
  46.             handler(this, e);  
  47.         }  
  48.     }  
  49.     public event PropertyChangedEventHandler PropertyChanged;  
  50.     #endregion  
  51.     #region IDisposable Members  
  52.     public void Dispose()  
  53.     {  
  54.         this.OnDispose();  
  55.     }  
  56.     /// <summary>  
  57.     /// 若支持IDisposable,请重写此方法,当被调用Dispose时会执行此方法。  
  58.     /// </summary>  
  59.     protected virtual void OnDispose()  
  60.     {  
  61.     }  
  62.     #endregion  
  63. }  

 

 

2.CommandBase.cs

[c-sharp] view plain copy print ?
  1. using System;  
  2. using System.Windows.Input;  
  3. /// <summary>  
  4. /// WPF MVVC设计模式命令基本功能类  
  5. /// </summary>  
  6. public class CommandBase : ICommand  
  7. {  
  8.     #region Private Fields  
  9.     private readonly Action<object> _command;  
  10.     private readonly Func<objectbool> _canExecute;  
  11.     #endregion  
  12.     #region Constructor  
  13.     /// <summary>  
  14.     /// 实例化一个CommandBase对象  
  15.     /// </summary>  
  16.     /// <param name="command">委托一个有object类型参数的命令执行函数</param>  
  17.     /// <param name="canExecute">委托一个有object类型参数的命令是否能被执行的函数(可选)</param>  
  18.     /// <exception cref="ArgumentNullException">参数command不可以为null引用</exception>  
  19.     public CommandBase(Action<object> command, Func<objectbool> canExecute = null)  
  20.     {  
  21.         if (command == null)  
  22.             throw new ArgumentNullException("command");  
  23.         _canExecute = canExecute;  
  24.         _command = command;  
  25.     }  
  26.     #endregion  
  27.     #region ICommand Members  
  28.     public void Execute(object parameter)  
  29.     {  
  30.         _command(parameter);  
  31.     }  
  32.     public bool CanExecute(object parameter)  
  33.     {  
  34.         if (_canExecute == null)  
  35.             return true;  
  36.         return _canExecute(parameter);  
  37.     }  
  38.     public event EventHandler CanExecuteChanged  
  39.     {  
  40.         add { CommandManager.RequerySuggested += value; }  
  41.         remove { CommandManager.RequerySuggested -= value; }  
  42.     }  
  43.     #endregion  
  44. }  

 

关于WPF MVVM设计模式文档(Josh Smith)

此代码是Josh Smith的范例修改版本。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的WPF MVVM模式的登录界面及代码: XAML代码: ```xml <Window x:Class="WpfApp1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApp1" Title="Login" Height="250" Width="350"> <Window.DataContext> <local:LoginViewModel /> </Window.DataContext> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Label Grid.Row="0" Grid.Column="0" Content="Username:"/> <TextBox Grid.Row="0" Grid.Column="1" Width="200" Margin="5" Text="{Binding Username}" /> <Label Grid.Row="1" Grid.Column="0" Content="Password:"/> <PasswordBox Grid.Row="1" Grid.Column="1" Width="200" Margin="5" Password="{Binding Password}" /> <Button Grid.Row="2" Grid.Column="1" Width="100" Margin="5" Content="Login" Command="{Binding LoginCommand}" IsDefault="True"/> <Label Grid.Row="3" Grid.Column="1" Content="{Binding ErrorMessage}" Foreground="Red" HorizontalAlignment="Center"/> <CheckBox Grid.Row="4" Grid.Column="1" Content="Remember Me" Margin="5" IsChecked="{Binding RememberMe}"/> </Grid> </Window> ``` ViewModel代码: ```csharp using System.ComponentModel; using System.Runtime.CompilerServices; using System.Windows; using System.Windows.Input; namespace WpfApp1 { public class LoginViewModel : INotifyPropertyChanged { private string _username; private string _password; private bool _rememberMe; private string _errorMessage; public string Username { get { return _username; } set { _username = value; OnPropertyChanged(); } } public string Password { get { return _password; } set { _password = value; OnPropertyChanged(); } } public bool RememberMe { get { return _rememberMe; } set { _rememberMe = value; OnPropertyChanged(); } } public string ErrorMessage { get { return _errorMessage; } set { _errorMessage = value; OnPropertyChanged(); } } public ICommand LoginCommand { get; set; } public LoginViewModel() { LoginCommand = new RelayCommand(Login, CanLogin); } private bool CanLogin() { return !string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(Password); } private void Login() { if (Username == "admin" && Password == "password") { if (RememberMe) { // Save login information to file or database } MessageBox.Show("Login successful!"); } else { ErrorMessage = "Invalid username or password"; } } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } ``` 其中,`RelayCommand`是一个实现了`ICommand`接口的自定义命令类,用于绑定按钮的点击事件。你可以在网上找到相关实现代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值