- 浏览: 399663 次
- 性别:
- 来自: 上海
文章分类
- 全部博客 (309)
- xaml C# wpf (0)
- scala java inner clas (1)
- Tools UML Eclipse UML2 (1)
- Timer .NET Framework (1)
- perl (6)
- python function paramter (1)
- Python Docstring (1)
- Python how to compare types (1)
- Python (8)
- java (5)
- C# (76)
- C# WPF (0)
- p4 (0)
- WPF (46)
- .net (6)
- xaml (1)
- javascript (40)
- windows (10)
- scala (4)
- winform (1)
- c++ (48)
- tools (12)
- cmd (1)
- os (0)
- CI (0)
- shell (0)
- C (2)
- haskell (49)
- functional (1)
- tool (1)
- gnu (1)
- linux (1)
- kaskell (0)
- svn (0)
- wcf (3)
- android (1)
最新评论
The topic originate/induce/beget/engender from the discussion of the DelegateCommand vs RoutedCommand. However, there are a grand topic covering with first the routed event.
Below is transcribed from the blog that is available WPF Routed Commands: Overview and Exampels ;
And it has several external links which you can find here:
http://msdn.microsoft.com/en-us/library/ms752308.aspx
http://msdn.microsoft.com/en-us/magazine/cc785480.aspx
http://msdn.microsoft.com/en-us/library/ff650631.aspx
The following are copied from the WPF Routed Commands: Overview and Exampels, some more example will be provided later to better illustrate the idea.
WPF Routed Commands: Overview and Examples
This article focuses on such WPF capability as routed commands, their structure and ways of using them. Apart from this, here we will describe benefits for the developer who use routed commands and problems that the developer can encounter.
WPF-routed commands give you a specific mechanism for hooking up UI controls such as toolbar buttons and menu items to handlers without introducing a lot of tight coupling and repetitive code into your application. The difference is that, contrary to an ordinary handler hooked up to a button or timer, the routed command separates the semantics and the object that invokes a command from the logic that executes the command. Routed commands give you three main things on top of normal event handling:
- Routed command source elements (invokers) can be decoupled from command targets (handlers)—they do not need direct references to one another, as they would if they were linked by an event handler.
- Routed commands will automatically enable or disable all associated UI controls when the handler indicates the command is disabled.
- Routed commands allow you to associate keyboard shortcuts and other forms of input gestures as another way to invoke the command.
Four Main Concepts of WPF Commanding
The routed command model in WPF can be broken up into four main concepts:
- Command — the action to be executed
- Command source — the object which invokes the command
- Command target — the object that the command is being executed on
- Command binding — the object which maps the command logic to the command
Command
WPF commands are custom implementations of the ICommand interface. ICommand has the Execute and CanExecute methods and the CanExecuteChanged event. Execute performs the execution logic of the command. CanExecute determines if the command can be executed for the current command target. If true value was returned, command can be executes and method Execute() is called. Method gradually calls for paired events PreviewExecuted and Executed as tasks to complete command in all target elements using binding elements. The CanExecuteChanged event is raised if the command manager that centralizes the commanding operations detects a change in the command source that might invalidate a command that has been raised but not yet executed by the command binding.
public interface ICommand
{
event EventHandler CanExecuteChanged;
bool CanExecute(object parameter);
void Execute(object parameter);
}
The Execute and CanExecute methods of the RoutedCommand class do not contain the application logic for the command, but rather they raise routed events that tunnel and bubble through the element tree until they encounter an object with a CommandBinding. The CommandBinding contains the handlers for these events and it is the handlers that perform the command.
WPF supplies a set of common routed commands spread across several classes: MediaCommands, ApplicationCommands, NavigationCommands, ComponentCommands and EditingCommands. The classes include only the RoutedCommand objects but not the implementation logic of the command. The implementation logic is the responsibility of the object on which the command is being executed on.
Command Source
A command source is the object which invokes the command. Command sources in WPF generally implement the ICommandSource interface.
ICommandSource exposes three properties: Command, CommandTarget and CommandParameter. Command is the command to execute when the command source is invoked. CommandTarget is the object on which to execute the command. If the CommandTarget is not set, the element with keyboard focus will be the command target. CommandParameter is a user-defined data type used to pass information to the handlers implementing the command.
public interface ICommandSource
{
ICommand Command { get; }
object CommandParameter { get; }
IInputElement CommandTarget { get; }
}
Typically, a command source will listen to the CanExecuteChanged event. This event informs the command source that the ability of the command to execute on the current command target may have changed. The command source can query the current status of the routed command by using the CanExecute method. The command source can then disable itself if the command cannot execute. An example of this is a MenuItem graying itself out when a command cannot execute.
The WPF classes that implement the ICommandSource are ButtonBase, MenuItem, Hyperlink and InputBinding.
In order for an object as a command to act as a command source, it must be associated with a command. There are a few ways to accomplish this. One way is to use InputBinding.
Another way is to add the KeyGesture object to the InputGestureCollection collection of the RoutedCommand object.
Example
KeyGesture openCommandKeyGesture = new KeyGesture(Key.O,
ModifierKeys.Control);
//Alternative 1
KeyBinding openCmdKeybinding = new KeyBinding(ApplicationCommands.Open,
openCommandKeyGesture);
InputBindings.Add(openCmdKeybinding);
//Alternative 2
ApplicationCommands.Open.InputGestures.Add(openCommandKeyGesture);
KeyGesture is a class that defines a keyboard combination that can be used to invoke a command. KeyGesture is a class that defines a keyboard combination that can be used to invoke a command. The same way MouseGesture class could be used.
Command Target
The command target is the element on which the command is executed. WPF elements inherit from the System.Windows.UIElement class, which has property-collection CommandBindings of CommandBindingCollection type. This helps to make this element listening for the team. With regards to a RoutedCommand the command target is the element at which routing of the Executed and CanExecute starts. If the CommandTarget is set on an ICommandSource and the corresponding command is not a RoutedCommand, the command target is ignored.
When command calls linked to it command object the last consequently executes CanExecute() и Execute()methods of ICommand interface. These methods generate command events that move through tree of elements checking their CommandBindings collections in order to identify CommandBinding object relevant to called command. When this binding element will be identified in listening element signed for the event Executed handler will be immediately executed.
The command source can explicitly set the command target. If the command target is not defined, the element with keyboard focus will be used as the command target. One of the benefits of using the element with keyboard focus as the command target is that it allows the application developer to use the same command source to invoke a command on multiple targets without having to keep track of the command target.
For example, if a MenuItem invokes the Paste command in an application that has a TextBox control and a PasswordBox, control, the target can be either depending on which control has keyboard focus. The TextBox and PasswordBox class implementations have a built-in command binding for the Cut command and encapsulate the clipboard handling for that command (and Copy and Paste as well). The active command handler is determined by a combination of where the command invoker and command handler are in the visual tree, and where the focus is in the UI. Usually, a command invoker looks for a command binding between its own location in the visual tree and the root of the visual tree. If it finds one, the bound command handler will determine whether the command is enabled and will be called when the command is invoked. If the command is hooked up to a control inside a toolbar or menu (or, more generally, a container that sets FocusManager.IsFocusScope = true), then some additional logic runs that also looks along the visual tree path from the root to the focus element for a command binding.
The following example shows how to explicitly set the command target in markup and in code behind.
Example
CommandTarget="{Binding ElementName=mainTextBox}" />
Command Binding
A CommandBinding object associates a command with the event handlers that implement the command. The CommandBinding contains a Command property, and PreviewExecuted, Executed, PreviewCanExecute and CanExecute events.
Command is the command that the CommandBinding is being associated with. The event handlers which are attached to the PreviewExecuted and Executed events implement the command logic. The event handlers attached to the PreviewCanExecute and CanExecute events determine if the command can execute on the current command target.
Each element of logical tree can be set as listening. But to get more flexibility of command binding in could be recommended to add root element for example into window.
The following example shows how to create a CommandBinding on the root Window of an application:
Example:
CanExecute="CommandBinding_CanExecute"
Executed="CommandBinding_Executed" />
Routed Commands: Problems and Solutions
Routed commands work nicely for simple user interface scenarios, hooking up toolbar and menu items, and handling those things that are inherently coupled to the keyboard focus (such as clipboard operations). Where routed commands are insufficient, however, is when you start building complex user interfaces, where your command handling logic is in supporting code for your view definitions and your command invokers are not always inside of a toolbar or menu.
The problem when you get into that arena is that the enabling and handling logic for a command may not be part of the visual tree directly; rather, it may be located in a presenter or presentation model. Additionally, the state that determines whether the command should be enabled may have no relation to where the command invokers and views are in the visual tree. You may also have scenarios where more than one handler is valid at a given time for a particular command.
To avoid problems related to visual tree location when working with routed commands, you should try to be simple. Usually, you need to be sure that handlers for a command are in the same element or higher in the tree then an element that is calling the command.
Conclusion
To sum up, today few developers are using routed commands on a daily basis. To me, the reasons are both the lack of awareness and experience in the developer community and problems that we encounter when developing complex GUIs. However, WPF routed commands are still an elegant way to link GUL controls to handlers, and often they can help you greatly.
Denis Glazkov, Software Developer, Digital Design
For preparing this article following materials were used:
http://msdn.microsoft.com/en-us/library/ms752308.aspx
http://msdn.microsoft.com/en-us/magazine/cc785480.aspx
http://msdn.microsoft.com/en-us/library/ff650631.aspx
发表评论
-
wpf - example to enhance ComboBox for AutoComplete
2014-09-19 15:56 1976first let’s see an example ... -
WPF – Virtualization – VirutalizationStackPanel and ItemsPanelTemplate
2013-08-05 21:55 1410Topic: WPF – Virtualization – ... -
wpf - BehaviorBase and one use examples
2013-06-18 18:41 1311Behavior is something that we ... -
WPF - Setting foreground color of Entire window
2013-06-13 16:00 1918You might as well as I would s ... -
WPF - Enhanced TabControl - TabControlEx aka Prerendering TabControl
2013-06-13 13:12 5330As an opening word, let's che ... -
wpf - ControlTemplate and AddLogicChild/RemoveLogicalChild
2013-06-10 15:42 1185Recently I was trying to debug ... -
wpf - default implicit style
2013-05-10 10:24 794We know that if you left out ... -
wpf - Style setter on the attached property
2013-05-08 14:54 2851I believe that you are familia ... -
wpf - specify enum values in xaml
2013-05-08 11:31 3585Many a situation you find tha ... -
wpf - IG xamDataGrid bind to XmlDataProvider with Xml Island
2012-12-18 14:28 1286Sometimes you may bind to some ... -
wpf - translate winform button/mouse event to wpf events
2012-12-12 17:37 2162It is common that we sometimes ... -
wpf - Freezable and its meaning
2012-09-27 12:38 0This article is based on the di ... -
wpf - Customize the grid lines for original wpf Grid control
2012-09-27 12:01 1458The System.WIndows.Controls.Gri ... -
c# - Convert from System.Drawing.Image to System.WIndows.Media.ImageSource
2012-09-25 14:27 7417In Previous discussion, we have ... -
wpf - Get Effective DependencyProperty value on a DependencyObject
2012-08-28 19:05 1044As discussed in my previous pos ... -
wpf - Default(Theme) style and its DefaultStyleKey
2012-08-28 17:54 1387As dicsused in the subsection o ... -
wpf - Dependency Property Value Precedence
2012-08-28 18:56 882A dependency property to an Dep ... -
wpf - WPF TemplateBinding vs RelativeSource TemplatedParent
2012-08-28 14:20 3713This is a post that summarizes ... -
wpf - ICutomTypeDescriptor , PropertyDescriptor and its use in PropertyGrid
2012-08-28 14:04 3580The type ICustomTypeDe ... -
wpf - tips to convert UI controls in WPF/Silverlight/Winforms into a Bitmap
2012-08-27 17:44 975In previous discussion, we have ...
相关推荐
**WPF命令(Command)** 命令模式是设计模式之一,WPF中的命令主要用于处理UI交互,分离用户界面与业务逻辑。命令分为两种类型:依赖属性命令(DependencyProperty-based Commands,如ButtonBase.Command)和实现...
总结起来,处理WPF MVVM中无`Command`属性控件的事件绑定主要有两种方式:一是利用`EventTrigger`和`InvokeCommandAction`,二是通过自定义`Behavior`。这两种方法都能够将控件的事件转换为ViewModel中的命令执行,...
在这个主题中,我们将深入探讨“WPF MVVM Command 02 触发器”,以及它们如何增强应用的功能。 **WPF MVVM Command** 在MVVM模式下,Command负责响应用户界面中的操作,比如按钮点击。命令接口`ICommand`定义了两...
**WPF Command 深入解析与自定义扩展** 在Windows Presentation Foundation (WPF) 中,Command 是一种关键的设计模式,用于实现用户界面与应用程序逻辑之间的解耦。它允许我们通过命令来执行业务逻辑,而无需直接在...
首先,WPF提供了两种主要的命令类型:`System.Windows.Input RelayCommand` 和 `System.Windows.Controls.Command`。`RelayCommand` 是MVVM(Model-View-ViewModel)模式中常用的命令实现,由Josh Smith首次提出,它...
WPF的控件中Command属性绑定了命令,与通常Click方式不同的是,它没有相应函数,这样的命令是这样执行的。
`Command Binding`是WPF中实现这一目标的一种优雅方式,它将视图(View)和视图模型(ViewModel)连接起来,遵循MVVM(Model-View-ViewModel)设计模式。 MVVM模式鼓励将业务逻辑和UI逻辑分离,`Command`对象承载了...
"WPF MVVM Command 01"可能是关于如何在WPF中实现MVVM模式中的命令机制的一个教程或项目实例。 在MVVM模式中,`Command`是一个关键概念,它连接了视图和视图模型之间的交互。视图通常由UI元素组成,如按钮,这些...
**WPF Prism 中的 Command 应用** WPF(Windows Presentation Foundation)是.NET框架下的一个UI开发库,它提供了一种强大的方式来构建美观且功能丰富的桌面应用程序。而Prism框架则是微软支持的一个用于开发WPF和...
首先,要实现事件绑定,我们需要引用`System.Windows.Interactivity`命名空间,这是WPF Blend SDK的一部分,提供了`EventTrigger`和`InvokeCommandAction`等类,让我们能够在XAML中绑定事件到ViewModel的命令。...
Eliminate unnecessary code by taking advantage of the MVVM pattern in Silverlight and WPF using this book and eBook - less code, fewer bugs Build an enterprise application using Silverlight and WPF,...
WPF WEBROWSER EVENT NEWWINDOW
However, the knowledge of how to do this is missing from a large part of the development community―even amongst those who work with WPF and Silverlight on a daily basis. Too often there is a reliance...
在Windows Presentation Foundation(WPF)中,Command是一种用于在视图和视图模型之间处理用户交互的机制。它是MVVM(Model-View-ViewModel)设计模式的重要组成部分,使得UI(用户界面)操作与业务逻辑解耦,提高...
This book was conceived from a need to explain the MVVM pattern and how it helps structure WPF and Silverlight applications. I had worked on a number of projects where these technologies were used ...
此外,WPF还提供了强大的事件处理机制,如根事件(Routed Event)和命令(Command),使得交互逻辑更加模块化和易于管理。 在WPF中,应用程序的基本组成包括窗口、控件、布局和样式等元素。通过这些组件,开发者可以...
笔记2:WPFCommand命令使用1、列表按钮绑定事件使用2、Command命令绑定传递指定控件对象 1、列表按钮绑定事件使用 Command=”{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListBox}, Path=...