- ICommand Интерфейс
- Определение
- Комментарии
- ICommand в среда выполнения Windows приложениях ICommand in Windows Runtime apps
- Использование атрибута XAML XAML Attribute Usage
- Значения XAML XAML Values
- Методы
- События
- Input Binding Класс
- Определение
- Примеры
- Комментарии
- Использование элемента объекта XAML XAML Object Element Usage
- Значения XAML XAML Values
- Конструкторы
- Свойства
- Методы
- События
ICommand Интерфейс
Определение
Определяет команду. Defines a command.
Комментарии
RoutedCommand и RoutedUICommand — это две реализации ICommand интерфейса в Windows Presentation Foundation (WPF). RoutedCommand and RoutedUICommand are two implementations of the ICommand interface in Windows Presentation Foundation (WPF).
ICommand в среда выполнения Windows приложениях ICommand in Windows Runtime apps
ICommandИнтерфейс — это контракт кода для команд, написанных на .NET для Среда выполнения Windows приложений. The ICommand interface is the code contract for commands that are written in .NET for Windows Runtime apps. Эти команды обеспечивают поведение команд для элементов пользовательского интерфейса, таких как среда выполнения Windows XAML Button и в частности AppBarButton . These commands provide the commanding behavior for UI elements such as a Windows Runtime XAML Button and in particular an AppBarButton . Если вы определяете команды для среда выполнения Windows приложений, которые вы используете, в основном те же методы, которые использовались для определения команд для приложения .NET. If you’re defining commands for Windows Runtime apps you use basically the same techniques you’d use for defining commands for a .NET app. Реализуйте команду, определив класс, реализующий ICommand и специально реализующий Execute метод. Implement the command by defining a class that implements ICommand and specifically implement the Execute method.
XAML для среда выполнения Windows не поддерживает x :Static , поэтому не пытайтесь использовать x:Static расширение разметки, если команда используется из среда выполнения Windows XAML. XAML for Windows Runtime does not support x :Static , so don’t attempt to use the x:Static markup extension if the command is used from Windows Runtime XAML. Кроме того, среда выполнения Windows не содержит ни одной предопределенной библиотеки команд, поэтому синтаксис XAML, показанный здесь, не применяется в тех случаях, когда вы реализуете интерфейс и определяете команду для среда выполнения Windows использования. Also, the Windows Runtime does not have any predefined command libraries, so the XAML syntax shown here doesn’t really apply for the case where you’re implementing the interface and defining the command for Windows Runtime usage.
Использование атрибута XAML XAML Attribute Usage
Значения XAML XAML Values
предефинедкласснаме predefinedClassName
Один из стандартных классов команд. One of the predefined command classes.
предефинедкомманднаме predefinedCommandName
Одна из предопределенных команд. One of the predefined commands.
кустомкласснаме customClassName
Пользовательский класс, содержащий пользовательскую команду. A custom class that contains the custom command. Для пользовательских классов обычно требуется xlmns сопоставление префиксов; см. раздел пространства имен и сопоставление пространств имен XAML для WPF XAML. Custom classes generally require an xlmns prefix mapping; see XAML Namespaces and Namespace Mapping for WPF XAML.
кустомкомманднаме customCommandName
Пользовательская команда. A custom command.
Методы
Определяет метод, который определяет, может ли данная команда выполняться в ее текущем состоянии. Defines the method that determines whether the command can execute in its current state.
Определяет метод, вызываемый при вызове данной команды. Defines the method to be called when the command is invoked.
События
Происходит при изменениях, влияющих на то, должна выполняться данная команда или нет. Occurs when changes occur that affect whether or not the command should execute.
Input Binding Класс
Определение
Представляет привязку между InputGesture и командой. Represents a binding between an InputGesture and a command. Этой командой потенциально является RoutedCommand. The command is potentially a RoutedCommand.
Примеры
В следующем примере показано, как использовать KeyBinding для привязки к KeyGesture 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.
В следующих примерах показано, как привязать пользовательскую команду к 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. GestureKey и GestureModifier Укажите ввод с клавиатуры; MouseGesture задает ввод с помощью мыши. GestureKey and GestureModifier specify the keyboard input; MouseGesture specifies the mouse input.
В следующем примере создается и инициализируется объект ColorChangeCommand , который является SimpleDelegateCommand . The following example creates and initializes the ColorChangeCommand , which is a SimpleDelegateCommand . В примере также определяется метод, выполняемый при вызове команды, и задаются GestureKey свойства, GestureModifier и MouseGesture . 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.
Наконец, в следующем примере создается пользовательский интерфейс. Finally, the following example creates the user interface. В примере добавляется KeyBinding и в MouseBinding StackPanel , который содержит Button и ListBox . The 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 свойство привязано к ColorChangeCommand . In each case, the CommandParameter property is bound to the selected item in the ListBox, and the Command property is bound to the ColorChangeCommand . KeyBinding.KeyСвойства, KeyBinding.Modifiers и MouseBinding.MouseAction привязаны к соответствующим свойствам SimpleDelegateCommand класса. The KeyBinding.Key, KeyBinding.Modifiers, and MouseBinding.MouseAction properties are bound to the corresponding properties on the SimpleDelegateCommand class.
Комментарии
Вы можете указать, что вводимые пользователем данные вызывают команду, создав InputBinding . You can specify that user input invokes a command by creating a InputBinding. Когда пользователь выполняет указанные входные данные, ICommand выполняется свойство, заданное для Command Свойства. When the user performs the specified input, the ICommand that is set to the Command property is executed.
Можно указать, что InputBinding метод вызывает команду, определенную для объекта, создав привязку для Command CommandParameter свойств, и CommandTarget . 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Можно определить для конкретного объекта или на уровне класса путем регистрации RegisterClassInputBinding с помощью CommandManager . An 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. Два существующих InputBinding производных класса, которые можно создать в XAML и могут задавать свойства в XAML, — это KeyBinding и MouseBinding . Two existing InputBinding-derived classes that can be instantiated in XAML and can set properties in XAML are KeyBinding and MouseBinding. Типичное свойство в программировании WPF, заданное в XAML и принимающее один или несколько InputBinding объектов в качестве значений, является UIElement.InputBindings свойством. The typical property in WPF 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
Значения XAML XAML Values
inputBindingDerivedClass
Производный класс InputBinding , который поддерживает синтаксис элементов объекта, например KeyBinding или MouseBinding . A derived class of InputBinding that supports object element syntax, such as KeyBinding or MouseBinding. См. заметки. See Remarks.
Конструкторы
Предоставляет базовую инициализацию для производных от InputBinding классов. Provides base initialization for classes derived from InputBinding.
Инициализирует новый экземпляр класса InputBinding с указанным именем команды и жестом ввода. Initializes a new instance of the InputBinding class with the specified command and input gesture.
Идентифицирует свойство зависимостей CommandParameter. Identifies the CommandParameter dependency property.
Идентифицирует свойство зависимостей Command. Identifies the Command dependency property.
Идентифицирует свойство зависимостей CommandTarget. Identifies the CommandTarget dependency property.
Свойства
Возвращает значение, которое указывает, можно ли сделать объект неизменяемым. Gets a value that indicates whether the object can be made unmodifiable.
(Унаследовано от Freezable)
Возвращает или задает объект ICommand, связанный с этой входной привязкой. Gets or sets the ICommand associated with this input binding.
Получает или задает специфические для команды данные для конкретной команды. Gets or sets the command-specific data for a particular command.
Получает или задает для команды целевой элемент. Gets or sets the target element of the command.
Возвращает объект DependencyObjectType , который заключает в оболочку тип CLR данного экземпляра. Gets the DependencyObjectType that wraps the CLR type of this instance.
(Унаследовано от DependencyObject)
Возвращает объект Dispatcher, с которым связан этот объект DispatcherObject. Gets the Dispatcher this DispatcherObject is associated with.
(Унаследовано от DispatcherObject)
Возвращает или задает объект InputGesture, связанный с этой входной привязкой. Gets or sets the InputGesture associated with this input binding.
Получает значение, указывающее, доступен ли объект для изменения в настоящее время. Gets a value that indicates whether the object is currently modifiable.
(Унаследовано от Freezable)
Получает значение, указывающее, является ли этот экземпляр в данный момент запечатанным (доступным только для чтения). Gets a value that indicates whether this instance is currently sealed (read-only).
(Унаследовано от DependencyObject)
Методы
Определяет, имеет ли вызывающий поток доступ к этому DispatcherObject. Determines whether the calling thread has access to this DispatcherObject.
(Унаследовано от DispatcherObject)
Очищает локальное значение свойства. Clears the local value of a property. Очищаемое свойство задается идентификатором DependencyProperty. The property to be cleared is specified by a DependencyProperty identifier.
(Унаследовано от DependencyObject)
Очищает локальное значение доступного только для чтения свойства. Clears the local value of a read-only property. Очищаемое свойство задается ключом DependencyPropertyKey. The property to be cleared is specified by a DependencyPropertyKey.
(Унаследовано от DependencyObject)
Создает изменяемый клон данного объекта 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)
Копирует базовые (не анимационные) значения свойств заданного объекта. Copies the base (non-animated) values of the properties of the specified object.
Создает редактируемую копию (глубокую копию) объекта Freezable с использованием его текущих значений. Creates a modifiable clone (deep copy) of the Freezable using its current values.
(Унаследовано от Freezable)
Копирует текущие значения свойств заданного объекта. Copies the current values of the properties of the specified object.
Приводит значение указанного свойства зависимостей. 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)
Инициализирует новый экземпляр класса Freezable. Initializes a new instance of the Freezable class.
(Унаследовано от Freezable)
Создает экземпляр класса InputBinding. Creates an instance of an InputBinding.
Определяет, является ли указанный DependencyObject эквивалентом текущего DependencyObject. Determines whether a provided DependencyObject is equivalent to the current DependencyObject.
(Унаследовано от DependencyObject)
Делает текущий объект неизменяемым и присваивает его свойству IsFrozen значение true . Makes the current object unmodifiable and sets its IsFrozen property to true .
(Унаследовано от Freezable)
Делает объект Freezable нередактируемым или проверяет, можно ли его сделать нередактируемым. Makes the Freezable object unmodifiable or tests whether it can be made unmodifiable.
(Унаследовано от Freezable)
Создает фиксированную копию объекта 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)
Создает экземпляр замороженной копии заданного объекта Freezable, используя базовые (не анимационные) значения свойства. Makes the instance a frozen clone of the specified Freezable by using base (non-animated) property values.
Создает фиксированную копию объекта 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)
Создает текущий экземпляр замороженной копии указанного объекта 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.
Возвращает хэш-код для данного объекта DependencyObject. Gets a hash code for this DependencyObject.
(Унаследовано от DependencyObject)
Создает специализированный перечислитель для определения свойств зависимостей, которые локально установили значения для данного DependencyObject. Creates a specialized enumerator for determining which dependency properties have locally set values on this DependencyObject.
(Унаследовано от DependencyObject)
Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.
(Унаследовано от Object)
Возвращает текущее действующее значение свойства зависимостей в этом экземпляре DependencyObject. Returns the current effective value of a dependency property on this instance of a DependencyObject.
(Унаследовано от DependencyObject)
Повторно вычисляет действующее значение для указанного свойства зависимостей. Re-evaluates the effective value for the specified dependency property.
(Унаследовано от DependencyObject)
Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.
(Унаследовано от Object)
Вызывается при изменении текущего объекта Freezable. Called when the current Freezable object is modified.
(Унаследовано от Freezable)
Обеспечивает создание соответствующих указателей контекста для элемента данных типа DependencyObjectType, который был только что задан. Ensures that appropriate context pointers are established for a DependencyObjectType data member that has just been set.
(Унаследовано от Freezable)
Этот элемент поддерживает инфраструктуру Windows Presentation Foundation (WPF) и не предназначен для непосредственного использования из кода. This member supports the Windows Presentation Foundation (WPF) infrastructure and is not intended to be used directly from your code.
(Унаследовано от Freezable)
Переопределяет реализацию DependencyObject для OnPropertyChanged(DependencyPropertyChangedEventArgs), чтобы также вызвать любой обработчик Changed в ответ на изменение свойства зависимостей типа Freezable. Overrides the DependencyObject implementation of OnPropertyChanged(DependencyPropertyChangedEventArgs) to also invoke any Changed handlers in response to a changing dependency property of type Freezable.
(Унаследовано от Freezable)
Вызывается каждый раз, когда обновляется действительное значение любого свойства зависимостей для данного 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)
Возвращает локальное значение свойства зависимостей, если таковое существует. Returns the local value of a dependency property, if it exists.
(Унаследовано от DependencyObject)
Обеспечивает доступ к Freezable из допустимого потока. Ensures 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)
Задает значение свойства зависимостей, не меняя источник значения. Sets the value of a dependency property without changing its value source.
(Унаследовано от DependencyObject)
Задает локальное значение свойства зависимостей, указанного идентификатором этого свойства. Sets the local value of a dependency property, specified by its dependency property identifier.
(Унаследовано от DependencyObject)
Задает локальное значение свойства зависимости только для чтения, определяемое идентификатором DependencyPropertyKey свойства зависимостей. Sets the local value of a read-only dependency property, specified by the DependencyPropertyKey identifier of the dependency property.
(Унаследовано от DependencyObject)
Возвращает значение, которое указывает, следует ли процессам сериализации выполнять сериализацию значения для предоставленного свойства зависимостей. Returns a value that indicates whether serialization processes should serialize the value for the provided dependency property.
(Унаследовано от DependencyObject)
Возвращает строку, представляющую текущий объект. Returns a string that represents the current object.
(Унаследовано от Object)
Обеспечивает наличие у вызывающего потока доступ к этому DispatcherObject. Enforces that the calling thread has access to this DispatcherObject.
(Унаследовано от DispatcherObject)
Вызывает событие Changed для объекта Freezable и вызывает его метод 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)
Проверяет, что объект 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)
События
Происходит, когда изменяется класс Freezable или объект, который входит в его состав. Occurs when the Freezable or an object it contains is modified.