InputBinding 类

定义

表示 InputGesture 和命令之间的绑定。Represents a binding between an InputGesture and a command. 此命令可能是 RoutedCommandThe command is potentially a RoutedCommand.

public ref class InputBinding : System::Windows::Freezable, System::Windows::Input::ICommandSource
public class InputBinding : System.Windows.Freezable, System.Windows.Input.ICommandSource
type InputBinding = class
    inherit Freezable
    interface ICommandSource
Public Class InputBinding
Inherits Freezable
Implements ICommandSource
继承
继承
派生
实现

示例

下面的示例演示如何使用 KeyBindingKeyGesture 绑定到 Open 命令。The following example shows how to use a KeyBinding to bind a KeyGesture to the Open command. 执行 key 势时,将调用 "打开" 命令。When the key gesture is performed, the Open command is invoked.

<Window.InputBindings>
  <KeyBinding Key="B"
              Modifiers="Control" 
              Command="ApplicationCommands.Open" />
</Window.InputBindings>

下面的示例演示如何将自定义命令绑定到 InputBinding 的对象。The following examples show how to bind a custom command to InputBinding objects. 这些示例创建一个应用程序,使用户可以通过执行下列操作之一来更改背景色:These examples create an application that enables the user to change the background color by performing one of the following actions:

第一个示例创建一个名为 SimpleDelegateCommand的类。The first example creates a class named SimpleDelegateCommand. 此类接受委托,以便创建命令的对象可以定义命令执行时发生的操作。This class accepts a delegate so that the object creating the command can define the action that occurs when the command executes. SimpleDelegateCommand 还定义属性,这些属性指定哪些键和鼠标输入调用命令。SimpleDelegateCommand also defines properties that specify what key and mouse input invokes the command. GestureKeyGestureModifier 指定键盘输入;MouseGesture 指定鼠标输入。GestureKey and GestureModifier specify the keyboard input; MouseGesture specifies the mouse input.

 // Create a class that implements ICommand and accepts a delegate.
public class SimpleDelegateCommand : ICommand
{
    // Specify the keys and mouse actions that invoke the command. 
    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 void Execute(object parameter)
    {
        _executeDelegate(parameter);
    }

    public bool CanExecute(object parameter) { return true; }
    public event EventHandler CanExecuteChanged;
}
' Create a class that implements ICommand and accepts a delegate. 
Public Class SimpleDelegateCommand
    Implements ICommand

    ' Specify the keys and mouse actions that invoke the command. 
    Private _GestureKey As Key
    Private _GestureModifier As ModifierKeys
    Private _MouseGesture As MouseAction

    Public Property GestureKey() As Key
        Get
            Return _GestureKey
        End Get
        Set(ByVal value As Key)
            _GestureKey = value
        End Set
    End Property

    Public Property GestureModifier() As ModifierKeys
        Get
            Return _GestureModifier
        End Get
        Set(ByVal value As ModifierKeys)
            _GestureModifier = value
        End Set
    End Property

    Public Property MouseGesture() As MouseAction
        Get
            Return _MouseGesture
        End Get
        Set(ByVal value As MouseAction)
            _MouseGesture = value
        End Set
    End Property

    Private _executeDelegate As Action(Of Object)

    Public Sub New(ByVal executeDelegate As Action(Of Object))
        _executeDelegate = executeDelegate
    End Sub

    Public Sub Execute(ByVal parameter As Object) _
        Implements ICommand.Execute

        _executeDelegate(parameter)
    End Sub

    Public Function CanExecute(ByVal parameter As Object) As Boolean _
        Implements ICommand.CanExecute

        Return True
    End Function

    Public Event CanExecuteChanged As EventHandler _
        Implements ICommand.CanExecuteChanged
End Class

下面的示例创建并初始化 ColorChangeCommand,这是一个 SimpleDelegateCommandThe following example creates and initializes the ColorChangeCommand, which is a SimpleDelegateCommand. 该示例还定义调用命令时执行的方法,并设置 GestureKeyGestureModifierMouseGesture 属性。The example also defines the method that executes when the command is invoked and sets the GestureKey, GestureModifier, and MouseGesture properties. 应用程序将在程序开始时调用 InitializeCommand 方法,例如在 Window的构造函数中。An application would call the InitializeCommand method when the program begins, such as in the constructor of a Window.

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;

// Switch the Background color between
// the original and selected color.
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;
    }
}
Public ReadOnly Property ChangeColorCommand() As SimpleDelegateCommand
    Get
        Return _changeColorCommand
    End Get
End Property

Private _changeColorCommand As SimpleDelegateCommand
Private originalColor As Brush, alternateColor As Brush

Private Sub InitializeCommand()
    originalColor = Me.Background

    _changeColorCommand = New SimpleDelegateCommand(Function(x) Me.ChangeColor(x))

    DataContext = Me
    _changeColorCommand.GestureKey = Key.C
    _changeColorCommand.GestureModifier = ModifierKeys.Control
    _changeColorCommand.MouseGesture = MouseAction.RightClick
End Sub

' Switch the Background color between 
' the original and selected color. 
Private Function ChangeColor(ByVal colorString As Object) As Integer

    If colorString Is Nothing Then
        Return 0
    End If

    Dim newColor As Color = DirectCast(ColorConverter.ConvertFromString(DirectCast(colorString, [String])), Color)

    alternateColor = New SolidColorBrush(newColor)

    If Brush.Equals(Me.Background, originalColor) Then
        Me.Background = alternateColor
    Else
        Me.Background = originalColor
    End If

    Return 0
End Function

最后,下面的示例创建用户界面。Finally, the following example creates the user interface. 该示例将 KeyBindingMouseBinding 添加到包含 ButtonListBoxStackPanelThe example adds a KeyBinding and a MouseBinding to a StackPanel that contains a Button and a ListBox. 当用户在 ListBox中选择某项时,他(她)可以将背景色更改为所选颜色。When the user selects an item in the ListBox, he or she can change the color of the background to the selected color. 在每种情况下,CommandParameter 属性都绑定到 ListBox中的选定项,Command 属性绑定到 ColorChangeCommandIn each case, the CommandParameter property is bound to the selected item in the ListBox, and the Command property is bound to the ColorChangeCommand. KeyBinding.KeyKeyBinding.ModifiersMouseBinding.MouseAction 属性绑定到 SimpleDelegateCommand 类上的相应属性。The KeyBinding.Key, KeyBinding.Modifiers, and MouseBinding.MouseAction properties are bound to the corresponding properties on the SimpleDelegateCommand class.

<StackPanel Background="Transparent">
  <StackPanel.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}"/>
  
  </StackPanel.InputBindings>
  
  <Button Content="Change Color" 
          Command="{Binding ChangeColorCommand}" 
          CommandParameter="{Binding ElementName=colorPicker, Path=SelectedItem}">
  </Button>

  <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>

注解

可以通过创建 InputBinding来指定用户输入调用命令。You can specify that user input invokes a command by creating a InputBinding. 当用户执行指定的输入时,将执行设置为 Command 属性的 ICommandWhen the user performs the specified input, the ICommand that is set to the Command property is executed.

您可以通过对 CommandCommandParameterCommandTarget 属性创建绑定,指定 InputBinding 调用在对象上定义的命令。You can specify that the InputBinding invokes a command that is defined on an object by creating a binding on the Command, CommandParameter, and CommandTarget properties. 这使你可以定义自定义命令并将其与用户输入相关联。This enables you to define a custom command and associate it with user input. 有关详细信息,请参阅 "示例" 部分中的第二个示例。For more information, see the second example in the Examples section.

可以通过向 CommandManager注册 RegisterClassInputBinding,在特定对象上或在类级别上定义 InputBindingAn InputBinding can be defined on a specific object or at the class level by registering a RegisterClassInputBinding with the CommandManager.

InputBinding 类本身不支持 XAML 用法,因为它不公开公共的无参数构造函数(有一个无参数的构造函数,但它受保护)。The InputBinding class itself does not support XAML usage because it does not expose a public parameterless constructor (there is a parameterless constructor, but it is protected). 但是,派生类可以公开公共构造函数,因此可以设置派生类的属性,这些属性是从 InputBinding 继承的,并使用 XAML 用法。However, derived classes can expose a public constructor and therefore can set properties on the derived class that are inherited from InputBinding with a XAML usage. 可以在 XAML 中实例化的两个现有 InputBinding派生类,并且可以在 XAML 中设置属性 KeyBindingMouseBindingTwo existing InputBinding-derived classes that can be instantiated in XAML and can set properties in XAML are KeyBinding and MouseBinding. 在 XAML 中设置的 WPFWPF 编程中的典型属性,并将一个或多个 InputBinding 对象作为值使用 UIElement.InputBindings 属性。The typical property in WPFWPF programming that is set in XAML and takes one or more InputBinding objects as values is the UIElement.InputBindings property.

XAML 对象元素用法XAML Object Element Usage

<inputBindingDerivedClass/><inputBindingDerivedClass…/>

XAML 值XAML Values

inputBindingDerivedClass
支持对象元素语法的 InputBinding 的派生类,如 KeyBindingMouseBindingA derived class of InputBinding that supports object element syntax, such as KeyBinding or MouseBinding. 请参阅“备注”。See Remarks.

构造函数

InputBinding()

提供从 InputBinding 派生的类的基初始化。Provides base initialization for classes derived from InputBinding.

InputBinding(ICommand, InputGesture)

用指定的命令和输入笔势初始化 InputBinding 类的新实例。Initializes a new instance of the InputBinding class with the specified command and input gesture.

字段

CommandParameterProperty

标识 CommandParameter 依赖项属性。Identifies the CommandParameter dependency property.

CommandProperty

标识 Command 依赖项属性。Identifies the Command dependency property.

CommandTargetProperty

标识 CommandTarget 依赖项属性。Identifies the CommandTarget dependency property.

属性

CanFreeze

获取一个值,该值指示是否可将对象变为不可修改。Gets a value that indicates whether the object can be made unmodifiable.

(继承自 Freezable)
Command

获取或设置与此输入绑定关联的 ICommandGets or sets the ICommand associated with this input binding.

CommandParameter

获取或设置特定命令的命令特定数据。Gets or sets the command-specific data for a particular command.

CommandTarget

获取或设置命令的目标元素。Gets or sets the target element of the command.

DependencyObjectType

获取对此实例的 DependencyObjectType 类型进行包装的 CLRCLRGets the DependencyObjectType that wraps the CLRCLR type of this instance.

(继承自 DependencyObject)
Dispatcher

获取与此 Dispatcher 关联的 DispatcherObjectGets the Dispatcher this DispatcherObject is associated with.

(继承自 DispatcherObject)
Gesture

获取或设置与此输入绑定关联的 InputGestureGets or sets the InputGesture associated with this input binding.

IsFrozen

获取一个值,该值指示对象当前是否可修改。Gets a value that indicates whether the object is currently modifiable.

(继承自 Freezable)
IsSealed

获取一个值,该值指示此实例当前是否为密封的(只读)。Gets a value that indicates whether this instance is currently sealed (read-only).

(继承自 DependencyObject)

方法

CheckAccess()

确定调用线程是否可以访问此 DispatcherObjectDetermines whether the calling thread has access to this DispatcherObject.

(继承自 DispatcherObject)
ClearValue(DependencyProperty)

清除属性的本地值。Clears the local value of a property. 要清除的属性由 DependencyProperty 标识符指定。The property to be cleared is specified by a DependencyProperty identifier.

(继承自 DependencyObject)
ClearValue(DependencyPropertyKey)

清除只读属性的本地值。Clears the local value of a read-only property. 要清除的属性由 DependencyPropertyKey 指定。The property to be cleared is specified by a DependencyPropertyKey.

(继承自 DependencyObject)
Clone()

创建 Freezable 的可修改克隆,以制作该对象值的深层副本。Creates a modifiable clone of the Freezable, making deep copies of the object's values. 在复制此对象的依赖属性时,此方法会复制表达式(可能不再解析),但不复制动画或其当前值。When copying the object's dependency properties, this method copies expressions (which might no longer resolve) but not animations or their current values.

(继承自 Freezable)
CloneCore(Freezable)

复制指定对象的属性的基(未经过动画处理的)值。Copies the base (non-animated) values of the properties of the specified object.

CloneCurrentValue()

使用 Freezable 的当前值创建其可修改复本(深层副本)。Creates a modifiable clone (deep copy) of the Freezable using its current values.

(继承自 Freezable)
CloneCurrentValueCore(Freezable)

复制指定对象的属性的当前值。Copies the current values of the properties of the specified object.

CoerceValue(DependencyProperty)

对指定依赖属性的值进行强制。Coerces the value of the specified dependency property. 通过对调用方 CoerceValueCallback 上存在的依赖属性的属性元数据中所指定的任何 DependencyObject 函数进行调用来完成此操作。This is accomplished by invoking any CoerceValueCallback function specified in property metadata for the dependency property as it exists on the calling DependencyObject.

(继承自 DependencyObject)
CreateInstance()

初始化 Freezable 类的新实例。Initializes a new instance of the Freezable class.

(继承自 Freezable)
CreateInstanceCore()

创建 InputBinding 的实例。Creates an instance of an InputBinding.

Equals(Object)

确定提供的 DependencyObject 是否等效于当前 DependencyObjectDetermines whether a provided DependencyObject is equivalent to the current DependencyObject.

(继承自 DependencyObject)
Freeze()

使当前对象不可修改,并且将其 IsFrozen 属性设置为 trueMakes the current object unmodifiable and sets its IsFrozen property to true.

(继承自 Freezable)
FreezeCore(Boolean)

使 Freezable 对象变为不可修改或测试是否可将其变为不可修改。Makes the Freezable object unmodifiable or tests whether it can be made unmodifiable.

(继承自 Freezable)
GetAsFrozen()

使用基(未经过动画处理的)属性值创建 Freezable 的冻结副本。Creates a frozen copy of the Freezable, using base (non-animated) property values. 由于副本已冻结,因此将通过引用复制任何冻结的子对象。Because the copy is frozen, any frozen sub-objects are copied by reference.

(继承自 Freezable)
GetAsFrozenCore(Freezable)

使用基(未经过动画处理的)属性值使该实例成为指定的 Freezable 的冻结复本。Makes the instance a frozen clone of the specified Freezable by using base (non-animated) property values.

GetCurrentValueAsFrozen()

使用当前属性值创建 Freezable 的冻结副本。Creates a frozen copy of the Freezable using current property values. 由于副本已冻结,因此将通过引用复制任何冻结的子对象。Because the copy is frozen, any frozen sub-objects are copied by reference.

(继承自 Freezable)
GetCurrentValueAsFrozenCore(Freezable)

使当前实例成为指定 Freezable 的冻结克隆。Makes the current instance a frozen clone of the specified Freezable. 如果对象具有动画依赖属性,则复制其当前的动画值。If the object has animated dependency properties, their current animated values are copied.

GetHashCode()

获取此 DependencyObject 的哈希代码。Gets a hash code for this DependencyObject.

(继承自 DependencyObject)
GetLocalValueEnumerator()

创建一个专用的枚举数,用于确定哪些依赖项属性在此 DependencyObject 上具有以本地方式设置的值。Creates a specialized enumerator for determining which dependency properties have locally set values on this DependencyObject.

(继承自 DependencyObject)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
GetValue(DependencyProperty)

DependencyObject 的此实例返回依赖属性的当前有效值。Returns the current effective value of a dependency property on this instance of a DependencyObject.

(继承自 DependencyObject)
InvalidateProperty(DependencyProperty)

重新评估指定依赖属性的有效值。Re-evaluates the effective value for the specified dependency property.

(继承自 DependencyObject)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
OnChanged()

修改当前 Freezable 对象时调用。Called when the current Freezable object is modified.

(继承自 Freezable)
OnFreezablePropertyChanged(DependencyObject, DependencyObject)

确保为刚刚设置的 DependencyObjectType 数据成员建立适当的上下文指针。Ensures that appropriate context pointers are established for a DependencyObjectType data member that has just been set.

(继承自 Freezable)
OnFreezablePropertyChanged(DependencyObject, DependencyObject, DependencyProperty)

此成员支持 Windows Presentation Foundation (WPF)Windows Presentation Foundation (WPF) 基础结构,但不能在代码中直接使用。This member supports the Windows Presentation Foundation (WPF)Windows Presentation Foundation (WPF) infrastructure and is not intended to be used directly from your code.

(继承自 Freezable)
OnPropertyChanged(DependencyPropertyChangedEventArgs)

每当更新此 DependencyObject 的任何依赖属性的有效值时调用。Invoked whenever the effective value of any dependency property on this DependencyObject has been updated. 更改的特定依赖属性将在事件数据中报告。The specific dependency property that changed is reported in the event data.

(继承自 DependencyObject)
ReadLocalValue(DependencyProperty)

如果存在,则返回依赖属性的本地值。Returns the local value of a dependency property, if it exists.

(继承自 DependencyObject)
ReadPreamble()

确保正在从有效的线程访问 FreezableEnsures that the Freezable is being accessed from a valid thread. Freezable 的继承者必须在任何 API 一开始读取不属于依赖项对象的数据成员时调用此方法。Inheritors of Freezable must call this method at the beginning of any API that reads data members that are not dependency properties.

(继承自 Freezable)
SetCurrentValue(DependencyProperty, Object)

设置依赖属性的值而不更改其值源。Sets the value of a dependency property without changing its value source.

(继承自 DependencyObject)
SetValue(DependencyProperty, Object)

设置依赖属性的本地值,该值由其依赖属性标识符指定。Sets the local value of a dependency property, specified by its dependency property identifier.

(继承自 DependencyObject)
SetValue(DependencyPropertyKey, Object)

设置一个只读依赖属性的本地值,该值由依赖属性的 DependencyPropertyKey 标识符指定。Sets the local value of a read-only dependency property, specified by the DependencyPropertyKey identifier of the dependency property.

(继承自 DependencyObject)
ShouldSerializeProperty(DependencyProperty)

返回一个值,该值指示序列化进程是否应序列化所提供的依赖属性的值。Returns a value that indicates whether serialization processes should serialize the value for the provided dependency property.

(继承自 DependencyObject)
ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(继承自 Object)
VerifyAccess()

强制调用线程具有此 DispatcherObject 的访问权限。Enforces that the calling thread has access to this DispatcherObject.

(继承自 DispatcherObject)
WritePostscript()

引发 FreezableChanged 事件并调用其 OnChanged() 方法。Raises the Changed event for the Freezable and invokes its OnChanged() method. Freezable 派生的类应在修改的类成员不存储为依赖属性的任何 API 的末尾调用此方法。Classes that derive from Freezable should call this method at the end of any API that modifies class members that are not stored as dependency properties.

(继承自 Freezable)
WritePreamble()

验证 Freezable 是否未被冻结,并且是否正在从有效的线程上下文中访问它。Verifies that the Freezable is not frozen and that it is being accessed from a valid threading context. Freezable 的继承项应当在任何 API 一开始写入不属于依赖项属性的数据成员时调用此方法。Freezable inheritors should call this method at the beginning of any API that writes to data members that are not dependency properties.

(继承自 Freezable)

事件

Changed

在修改 Freezable 或其包含的对象时发生。Occurs when the Freezable or an object it contains is modified.

(继承自 Freezable)

适用于

另请参阅