wpf - input binding examples

本文详细介绍了输入绑定的概念及其在应用程序中如何通过键盘输入和鼠标操作触发命令。通过创建自定义命令类和使用InputBindings类,实现了用户可以通过按下特定键(如Ctrl+C)或执行右键点击等操作来执行特定任务。此外,通过XAML文件配置了具体的输入绑定,使得用户能够通过界面元素进行操作。示例代码展示了如何设置命令、键绑定、修改键和鼠标动作绑定,从而实现在不同场景下灵活触发命令的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Input binding is the mechanism that you can invoke a command by some input measures, such as mouse input or keyboard input. 

 

 

The concrete classes to InputBindings are MouseBinding and KeyBinding. 

 

 

Since Input bindings are something that you may use often, below shows you an example on how to use the Input Bindings. (normally you will create input binding on parent element so that you can fire the command from a bigger container )

 

 

Suppose that you can create a class that implements the ICommand, and this class has some input gestures which indicate what input it expects to fire the commands. 

 

 

 

namespace InputBindingsTest
{
  public class SimpleDelegateCommand  : ICommand
  {

    public Key GestureKey { get; set; }
    public ModifierKeys GestureModifier { get; set; }
    public MouseAction MouseGesture { get; set; }

    Action<object> _executeDelegate;

    public SimpleDelegateCommand(Action<object> executeDelegate)
    {
      _executeDelegate = executeDelegate;
    }

    public bool CanExecute(object parameter)
    {
      return true;
      // if the CanExecute changes, raise the OnCanExecutedChanged()
      //OnCanExecutedChanged(null);
    }

    public event EventHandler CanExecuteChanged;

    protected virtual void OnCanExecutedChanged(EventArgs eventargs)
    {
      var changed = CanExecuteChanged;
      if (changed != null)
      {
        changed(this, eventargs);
      }
    }

    public void Execute(object parameter)
    {
      _executeDelegate(parameter);
    }
  }
}
 

 

and with this class, we are going to create a concrete command , which represents a action to change the background of container. 

 

The name of the Command is ChangeColorCommand, and we want to indicate that user can fire the command through the use of "Ctrl + C" or "Right Mouse ClicK"; Also, in this source file, the handler to the ChangeColorCommand is also defined.

 

 

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


    public SimpleDelegateCommand ChangeColorCommand
    {
      get { return changeColorCommand; }
    }

    private SimpleDelegateCommand changeColorCommand;


    private void InitializeCommand()
    {
      originalColor = this.Background;
      changeColorCommand = new SimpleDelegateCommand(x => this.ChangeColor(x));
      DataContext = this;
      changeColorCommand.GestureKey = Key.C;
      changeColorCommand.GestureModifier = ModifierKeys.Control;
      changeColorCommand.MouseGesture = MouseAction.RightClick;
    }

    private Brush originalColor, alternateColor;

    private void ChangeColor(object colorString)
    {
      if (colorString == null)
      {
        return;
      }

      Color newColor = (Color)ColorConverter.ConvertFromString((string)colorString);
      alternateColor = new SolidColorBrush(newColor);

      if (this.Background == originalColor)
      {
        this.Background = alternateColor;
      }
      else
      {
        this.Background = originalColor;
      }
    }

  }
}
 

 

 

Now, to make the Input binding really effective, below is the xaml file. where we set up the Input binding on the container element (in this case, the MainWindow), and we uses the concrete binding such as KeyBinding and the MouseBinding;

 

 

<Window x:Class="InputBindingsTest.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">
    <Window.InputBindings>
        <KeyBinding Command="{Binding ChangeColorCommand}"
                CommandParameter="{Binding ElementName=colorPicker, Path=SelectedItem}"
                Key="{Binding ChangeColorCommand.GestureKey}"
                Modifiers="{Binding ChangeColorCommand.GestureModifier}"/>
        <MouseBinding Command="{Binding ChangeColorCommand}"
                  CommandParameter="{Binding ElementName=colorPicker, Path=SelectedItem}"
                  MouseAction="{Binding ChangeColorCommand.MouseGesture}"/>
    </Window.InputBindings>
    <StackPanel Background="Transparent">
        <Button Content="Change Color"
                Command="{Binding ChangeColorCommand}"
                CommandParameter="{Binding ElementName=colorPicker, Path=SelectedItem}" />
        <ListBox Name="colorPicker"
           Background="Transparent"
           xmlns:sys="clr-namespace:System;assembly=mscorlib">
            <sys:String>Red</sys:String>
            <sys:String>Green</sys:String>
            <sys:String>Blue</sys:String>
            <sys:String>Yellow</sys:String>
            <sys:String>Orange</sys:String>
            <sys:String>Purple</sys:String>
        </ListBox>
    </StackPanel>
</Window>
 

 

now you can change the color of the background either through the use of "Right Mouse" click or you can simpley press "Ctrl + C";

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值