(WPF按钮命令绑定)WPF MVVM Button Bind Command

1.xaml按钮设置  Command="{Binding ButtonIncrease}" 这里是命令绑定

       
                    
                    
                    
                

2.编写ViewModel

using InfusionBagSmartLabeler.Common.Command;
using InfusionBagSmartLabeler.Model;
using InfusionBagSmartLabeler.utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Input;

namespace InfusionBagSmartLabeler.ViewModel
{
    public class NetworkViewModel : INotifyPropertyChanged
    { 
        private int _BeltSpeed = int.Parse(Config.getInstance().getConfig("BeltSpeed"));
        //public ICommand MyCommand => new MyCommand(MyAction, MyCanExec);
        bool isCanExec = true;

        public ICommand ButtonIncrease => new MyCommand(ButtonIncreaseAction, MyCanExec); 
        public ICommand ButtonDecrease => new MyCommand(ButtonDecreaseAction, MyCanExec);
 
 

        public event PropertyChangedEventHandler PropertyChanged;

 

        private bool MyCanExec(object parameter)
        {
            return isCanExec;
        }

        private void ButtonIncreaseAction(object parameter)
        {
            if (BeltSpeed < 100)
            {
                BeltSpeed = BeltSpeed + 1;
            }
          
            Debug.WriteLine($"BeltSpeed {BeltSpeed}"); 
        }

        private void ButtonDecreaseAction(object parameter)
        {
            if (BeltSpeed > 1)
            {
                BeltSpeed = BeltSpeed - 1;
            }

            Debug.WriteLine($"BeltSpeed {BeltSpeed}");
             
        }

    }
}

3.定义MyCommand继承自ICommand 

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Input;

namespace InfusionBagSmartLabeler.Common.Command
{
   public class MyCommand :ICommand
    {
        private readonly Action execAction;
        private readonly Func changeFunc;

        public MyCommand(Action execAction,Func changeFunc)
        {
            this.execAction = execAction;
            this.changeFunc = changeFunc;
        }

        public event EventHandler CanExecuteChanged;

        public bool CanExecute(object parameter)
        {
            return this.changeFunc.Invoke(parameter);
        }

        public void Execute(object parameter)
        {
            this.execAction.Invoke(parameter);
        }
    }
}
 
  

你可能感兴趣的:(#,.net,core,#,WPF,wpf,microsoft,c#)