1.xaml按钮设置 Command="{Binding ButtonIncrease}" 这里是命令绑定
<StackPanel Grid.Column="1" Orientation="Horizontal">
<Button Content="+" Command="{Binding ButtonIncrease}" Height="20" Margin="5,-2,0,0"
HorizontalAlignment="Center" VerticalAlignment="Center"></Button>
<TextBox x:Name="tb_BletSpeed" IsEnabled="False" HorizontalAlignment="Left" Margin="10,10,0,0" Text="{Binding BeltSpeed}"
TextWrapping="Wrap" VerticalAlignment="Top" Width="70"/>
<Button Content="-" Command="{Binding ButtonDecrease}" Height="20" Margin="5,-2,0,0"></Button>
</StackPanel>
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<object> execAction;
private readonly Func<object, bool> changeFunc;
public MyCommand(Action<object> execAction,Func<object,bool> 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);
}
}
}