且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

RoutedUICommand PreviewExecuted漏洞?

更新时间:2023-09-11 21:53:28


编辑2:从查看源代码,它看来,在内部它的工作方式是:




  1. 的UIElement 通话 CommandManager.TranslateInput()反应用户输入(鼠标或键盘)。

  2. 命令管理然后通过 CommandBindings 那张>不同层面寻找与输入相关的命令。

  3. 当命令找到了 CanExecute()方法被调用,如果返回真正()执行被称为

  4. 在的的RoutedCommand 每做essencially同样的事情的方法情况下 - 它提出了一个对附着事件 CommandManager.PreviewCanExecuteEvent CommandManager.CanExecuteEvent (或 PreviewExecutedEvent ExecutedEvent )的的UIElement 启动该进程。这结束了第一阶段。

  5. 现在,在的UIElement 有这四个事件的注册类处理程序和这些处理程序只需调用 CommandManager.OnCanExecute() CommandManager.CanExecute()(用于预览和实际事件)。

  6. 只有在这里 CommandManager.OnCanExecute() CommandManager.OnExecute()其中,处理程序登记方法与的CommandBinding 被调用。如果没有任何发现命令管理事件转移到的UIElement 的母公司,新的周期开始,直到该指令被处理或达到视觉树的根。


块引用>

如果你看一下一流的CommandBinding源代码有OnExecuted()方法,它负责调用,通过您的CommandBinding注册PreviewExecuted的处理程序和执行的事件。有该位有:

  PreviewExecuted(发件人,E); 
e.Handled = TRUE;

这设置事件的处理您的PreviewExecuted处理程序返回后马上所以执行的不叫




编辑1:纵观CanExecute&安培; PreviewCanExecute事件有一个关键的区别:

  PreviewCanExecute(发件人,E); 
如果(e.CanExecute)
{
e.Handled = TRUE;
}



设置进行处理,以真正是有条件的在这里,所以它是谁决定是否程序员要不要继续进行CanExecute。根本就没有设置CanExecuteRoutedEventArgs的CanExecute为true,你PreviewCanExecute处理程序和CanExecute处理程序将被调用。预览事件



至于 ContinueRouting 属性 - 设置为false时它可以防止进一步的路由预览事件,但它不以任何方式影响主要​​有以下事件。


块引用>

请注意,当处理程序通过的CommandBinding注册的,它只能这样。



如果你仍然想同时拥有PreviewExecuted和执行来运行,你有两种选择:




  1. 您可以可以拨打从PreviewExecuted处理程序中执行路由命令()方法。想到它 - 因为你的PreviewExecuted完成之前调用执行的处理程序,你可能会遇到同步问题。对我来说,这看起来并不像一个很好的路要走。

  2. 您可以通过分别注册PreviewExecuted处理CommandManager.AddPreviewExecutedHandler()静态方法。这将直接自UIElement类调用,并不会涉及的CommandBinding。 编辑2:看看在文章开头的4点 - 这是我们加入的处理程序事件



从它的外观 - 这是做故意这样。为什么?人们只能猜测...


I'm building an application using the MVVM design pattern and I want to make use of the RoutedUICommands defined in the ApplicationCommands class. Since the CommandBindings property of a View (read UserControl) isn't a DependencyProperty we can't bind CommandBindings defined in a ViewModel to the View directly. I solved this by defining an abstract View class which binds this programmatically, based on a ViewModel interface which ensures every ViewModel has an ObservableCollection of CommandBindings. This all works fine, however, in some scenarios I want to execute logic which is defined in different classes (the View and ViewModel) same command. For instance, when saving a document.

In the ViewModel the code saves the document to disk:

private void InitializeCommands()
{
    CommandBindings = new CommandBindingCollection();
    ExecutedRoutedEventHandler executeSave = (sender, e) =>
    {
        document.Save(path);
        IsModified = false;
    };
    CanExecuteRoutedEventHandler canSave = (sender, e) => 
    {
        e.CanExecute = IsModified;
    };
    CommandBinding save = new CommandBinding(ApplicationCommands.Save, executeSave, canSave);
    CommandBindings.Add(save);
}

At first sight the previous code is all I wanted to do, but the TextBox in the View to which the document is bound, only updates its Source when it loses its focus. However, I can save a document without losing focus by pressing Ctrl+S. This means the document is saved before the changes where Updated in the source, effectively ignoring the changes. But since changing the UpdateSourceTrigger to PropertyChanged isn't a viable option for performance reasons, something else must force an update before saving. So I thought, lets use the PreviewExecuted event to force the update in the PreviewExecuted event, like so:

//Find the Save command and extend behavior if it is present
foreach (CommandBinding cb in CommandBindings)
{
    if (cb.Command.Equals(ApplicationCommands.Save))
    {
        cb.PreviewExecuted += (sender, e) =>
        {
            if (IsModified)
            {
                BindingExpression be = rtb.GetBindingExpression(TextBox.TextProperty);
                be.UpdateSource();
            }
            e.Handled = false;
        };
    }
}

However, assigning an handler to the PreviewExecuted event seems to cancel the event altogether, even when I explicitly set the Handled property to false. So the executeSave eventhandler I defined in the previous code sample isn't executed anymore. Note that when I change the cb.PreviewExecuted to cb.Executed both pieces of code do execute, but not in the correct order.

I think this is a Bug in .Net, because you should be able to add a handler to PreviewExecuted and Executed and have them be executed in order, provided you don't mark the event as handled.

Can anyone confirm this behavior? Or am I wrong? Is there a workaround for this Bug?

EDIT 2: From looking at the source code it seems that internally it works like that:

  1. The UIElement calls CommandManager.TranslateInput() in reaction to user input (mouse or keyboard).
  2. The CommandManager then goes through CommandBindings on different levels looking for a command associated with the input.
  3. When the command is found its CanExecute() method is called and if it returns true the Executed() is called.
  4. In case of RoutedCommand each of the methods does essencially the same thing - it raises a pair of attached events CommandManager.PreviewCanExecuteEvent and CommandManager.CanExecuteEvent (or PreviewExecutedEvent and ExecutedEvent) on the UIElement that initiated the process. That concludes the first phase.
  5. Now the UIElement has class handlers registered for those four events and these handlers simply call CommandManager.OnCanExecute() and CommandManager.CanExecute() (for both preview and actual events).
  6. It is only here in CommandManager.OnCanExecute() and CommandManager.OnExecute() methods where the handlers registered with CommandBinding are invoked. If there are none found the CommandManager transfers the event up to the UIElement's parent, and the new cycle begins until the command is handled or the root of the visual tree is reached.

If you look at the CommandBinding class source code there is OnExecuted() method that is responsible for calling the handlers you register for PreviewExecuted and Executed events through CommandBinding. There is that bit there:

PreviewExecuted(sender, e); 
e.Handled = true;

this sets the event as handled right after your PreviewExecuted handler returns and so the Executed is not called.

EDIT 1: Looking at CanExecute & PreviewCanExecute events there is a key difference:

  PreviewCanExecute(sender, e); 
  if (e.CanExecute)
  { 
    e.Handled = true; 
  }

setting Handled to true is conditional here and so it is the programmer who decides whether or not to proceed with CanExecute. Simply do not set the CanExecuteRoutedEventArgs's CanExecute to true in your PreviewCanExecute handler and the CanExecute handler will be called.

As to ContinueRouting property of Preview event - when set to false it prevents the Preview event from further routing, but it does not affect the following main event in any way.

Note, that it only works this way when handlers are registered through CommandBinding.

If you still want to have both PreviewExecuted and Executed to run you have two options:

  1. You can can call Execute() method of the routed command from within PreviewExecuted handler. Just thinking about it - you might run into sync issues as you're calling Executed handler before the PreviewExecuted is finished. To me this doesn't look like a good way to go.
  2. You can register PreviewExecuted handler separately through CommandManager.AddPreviewExecutedHandler() static method. This will be called directly from UIElement class and will not involve CommandBinding. EDIT 2: Look at the point 4 at the beginning of the post - these are the events we're adding the handlers for.

From the looks of it - it was done this way on purpose. Why? One can only guess...