WPF A simple example of implementing ICommand Binding

来源:互联网 发布:泰坦尼克号细节知乎 编辑:程序博客网 时间:2024/05/22 22:59

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.

 

原创粉丝点击