WPF A simple example of implementing ICommand Binding

When we wrote the windows form application and wanted to trigger the event when clicked the button. we use to duble click the button in the design and then enter the function writing the comments. But if the form contains lots of controls, this process may be not wise.  Command binding can easy solve this problem. But it exist in WPF. These are my personal understanding. If they are not correct. Please raise your comments.

 

Let me show you method binding function. We will implement the interface ICommand. It is one of the ways to implementing the Command Binding.

 

First we create a WPF project named MyFirstWPFApp

Then we can add a class named MyCommand. This class will inheritICommand.We put the class in a folder named Tools.

The ICommand contains three parts of content as below:

 Then we implement it.

using System;
using System.Windows.Input;

namespace MyFirstWPF.Tools
{
    class MyCommand:ICommand
    {
        Action executeMethod;
        Func<bool> canExcuteMethod;
        bool canexecute = true;

        public MyCommand(Action executeMehtod)
        {
            this.executeMethod = executeMehtod;
        }

        public MyCommand(Action executeMethod, Func<bool> canExecuteMethod)
        {
            this.executeMethod = executeMethod;
            this.canExcuteMethod = canExecuteMethod;
        }

        #region Implement ICommand

        public bool CanExecute(object parameter)
        {
            if (canExcuteMethod != null)
            {
                bool _result = canExcuteMethod();
                if (canexecute != _result)
                {
                    canexecute = _result;
                    EventHandler handler = CanExecuteChanged;
                    if (handler != null)
                    {
                        handler(parameter, EventArgs.Empty);
                    }
                }
            }

            return canexecute;
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            executeMethod();
            if (canExcuteMethod != null)
            {
                CanExecuteChanged(parameter, EventArgs.Empty);
            }
        }

        public void RaiseCanExecuteChanged()
        {
            EventHandler handler = CanExecuteChanged;

            if (handler != null)
                handler(this, EventArgs.Empty);
        }

        #endregion
    }

 

Next step we can use the MyCommand in the project. So we design in MainWindow.xaml to implement it simply.

<Window x:Class="MyFirstWPFApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <StackPanel>
            <Rectangle Height="30"/>
            <Button Content="Show Message" Name="btnShow" Width="121" Command="{Binding ShowMessageCommand}"/>
            <Rectangle Height="30"/>
            <Button Content="Enable to show again" Name="btnAgain" Width="121" Command="{Binding EnableShowAgainCommand}"/>
        </StackPanel>
    </Grid>
</Window>

 

as you see the two buttons' Command have binding different method. When click the button btnShow. The method ShowMessageCommand would be excuted. But where is the method? Which class contains it? The must be done by ourselves. So we can create a class named MainWindowViewModel.cs. We will write these two method (bindinged by button btnShow and button btnAgain) in this class.
 

using System.Windows;
using MyFirstWPF.Tools;

namespace MyFirstWPF.ViewModels
{
    class MainWindowViewModel
    {
        public MyCommand ShowMessageCommand { get; set; }
        public MyCommand EnableShowAgainCommand { get; set; }

        private bool CanExe { get; set; }

        public MainWindowViewModel()
        {
            ShowMessageCommand = new MyCommand(ExecuteShowMessageCommand, CanExecuteShowMessageCommand);
            EnableShowAgainCommand = new MyCommand(ExecuteEnableShowMessageCommand);

            CanExe = true;
        }

        private bool CanExecuteShowMessageCommand()
        {
            return CanExe;
        }
        private void ExecuteShowMessageCommand()
        {
            CanExe = false;
            MessageBox.Show("Hello");
        }

        public void ExecuteEnableShowMessageCommand()
        {
            CanExe = !CanExe;
            ShowMessageCommand.RaiseCanExecuteChanged();
        }
    }
}


How could the Command of the button could find the method in MainWindowViewModel.cs? So the next step is the center. We should modify the MainWindow.xaml.cs

using System.Windows;
using MyFirstWPF.ViewModels;

namespace MyFirstWPF
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            this.DataContext = new MainWindowViewModel();
        }
    }
}


Finaly I organize the source file like below.

 

The finaly step is running it project.

The result is below. We click the Show Message. It wil show a message box. And this button would not be enabled. Then you click the Enable to show again, the button Show Message would be enabled again.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值