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. 執行按鍵手勢時,會叫用 Open 命令。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:

  • 按一下按鈕。Clicking a button.

  • 按 CTRL + C。Pressing CTRL+C.

  • 以滑鼠右鍵按一下 StackPanel (在 ListBox外)。Right-clicking a StackPanel (outside the ListBox).

第一個範例會建立名為 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.

您可以指定 InputBinding 叫用在物件上定義的命令,方法是在 CommandCommandParameterCommandTarget 屬性上建立系結。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.

InputBinding 可以在特定物件上或在類別層級上定義,方法是向 CommandManager註冊 RegisterClassInputBindingAn 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 中具現化並可在 XAML 中設定屬性的兩個現有 InputBinding衍生類別,會 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 類別的新執行個體 (Instance)。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 和目前的 DependencyObject 是否相等。Determines 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()

確定 Freezable 是從有效的執行緒進行存取。Ensures that the Freezable is being accessed from a valid thread. 如果 API 會讀取非相依性屬性的資料成員,則 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. 在任何 API 修改未以相依性屬性儲存的類別成員之後,衍生自 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. 在任何 API 將資料寫入至非相依性屬性的資料成員之前,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)

適用於

另請參閱