WPF之MVVM(Step2)——自己实现DelegateCommand:ICommand

在自己实现MVVM时,上一篇的实现方式基本是不用,因其对于命令的处理不够方便,没写一个命令都需要另加一个Command的类。此篇主要介绍DelegateCommand来解决上面所遇到的问题。

首先,我们创建自己的DelegateCommand。

代码如下:

 /// <summary>
    /// 实现DelegateCommand
    /// </summary>
    class MyDelegateCommand : ICommand
    {
        /// <summary>
        /// 命令所需执行的事件
        /// </summary>
        public Action<object> ExecuteCommand { get; set; }
        /// <summary>
        /// 命令是否可用所执行的事件
        /// </summary>
        public Func<object, bool> CanExecuteCommand { get; set; }

        public MyDelegateCommand()
        {
        }

        public MyDelegateCommand(Action<object> execute, Func<object, bool> canexecute)
        {
            ExecuteCommand = execute;
            CanExecuteCommand = canexecute;
        }

        /// <summary>
        /// 命令可用性获取
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public bool CanExecute(object parameter)
        {
            return CanExecuteCommand(parameter);
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        /// <summary>
        /// 命令具体执行
        /// </summary>
        /// <param name="parameter"></param>
        public void Execute(object parameter)
        {
            ExecuteCommand(parameter);
        }
    }

 

其中的重点是利用两个委托,将方法的实现分离出去,接下来看我们的ViewModel:

  class TestViewModel : INotifyPropertyChanged
    {

        private string teststr;
        /// <summary>
        /// 待通知字符串
        /// </summary>
        public string TestStr
        {
            get { return teststr; }
            set
            {
                teststr = value;
                RaiseChanged("TestStr");
            }
        }

        /// <summary>
        /// 测试命令
        /// </summary>
        public ICommand TestCommand { get; set; }


        public TestViewModel()
        {
            TestCommand = new MyDelegateCommand();
            (TestCommand as MyDelegateCommand).ExecuteCommand = Test;
            (TestCommand as MyDelegateCommand).CanExecuteCommand = CanTest;
            //or
            //TestCommand = new MyDelegateCommand(Test, CanTest);
        }

        int i = 0;
        /// <summary>
        /// testcommand执行的方法
        /// </summary>
        /// <param name="para"></param>
        private void Test(object para)
        {
            i++;
            TestStr = i.ToString();
        }
        /// <summary>
        /// testcommand是否可用
        /// </summary>
        /// <param name="para"></param>
        /// <returns></returns>
        private bool CanTest(object para)
        {
            return true;
        }

        #region INotifyPropertyChanged接口实现
        public void RaiseChanged(string propertyname)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyname));
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
        #endregion
    }

其中的Test,CanTest就是之前写在Command中的实现,通过此实现,我们可以将界面呈现逻辑全部集中到ViewModel中。

其界面还是一样使用上一篇的。

 


项目代码托管地址: https://wpfmvvm.codeplex.com/

转载于:https://www.cnblogs.com/huaxia283611/p/4194665.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这里我可以给你一个WPF使用MvvmLight实现MVVM的工程实例。 首先,你需要在Visual Studio中安装MvvmLight框架。可以通过NuGet来安装MvvmLight库,具体步骤如下: 1. 在Visual Studio中打开你的WPF工程。 2. 在Solution Explorer窗口中右键单击工程,选择“Manage NuGet Packages”。 3. 在“NuGet Package Manager”窗口中,在搜索框中输入“MvvmLight”,选择“MvvmLight”并安装。 接下来,我们就可以开始实现MVVM模式了。 1. 创建一个新的ViewModel类,继承自ViewModelBase类。 ```csharp using GalaSoft.MvvmLight; public class MainViewModel : ViewModelBase { //ViewModel的属性和命令 } ``` 2. 在ViewModel中实现需要绑定的属性和命令。 ```csharp private string _message; public string Message { get { return _message; } set { if (_message != value) { _message = value; RaisePropertyChanged(() => Message); } } } private RelayCommand _showMessageCommand; public RelayCommand ShowMessageCommand { get { if (_showMessageCommand == null) { _showMessageCommand = new RelayCommand(() => { MessageBox.Show(Message); }); } return _showMessageCommand; } } ``` 3. 在View中绑定ViewModel的属性和命令。 ```xaml <Window x:Class="WpfApp1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApp1" xmlns:vm="clr-namespace:WpfApp1.ViewModel" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <Window.DataContext> <vm:MainViewModel /> </Window.DataContext> <Grid> <Grid.RowDefinitions> <RowDefinition Height="*" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <TextBox Text="{Binding Message, UpdateSourceTrigger=PropertyChanged}" /> <Button Grid.Row="1" Content="Show Message" Command="{Binding ShowMessageCommand}" /> </Grid> </Window> ``` 在这个例子中,我们创建了一个MainViewModel类,其中包含了一个Message属性和一个ShowMessageCommand命令。在View中,我们使用DataContext将ViewModel实例与View绑定,并使用Binding将ViewModel的属性和命令绑定到View上。 这样,我们就成功地使用MvvmLight实现MVVM模式。当用户在TextBox中输入文字并点击Button时,将会弹出一个对话框显示用户输入的文字。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值