2010-07-30 25 views
0

讓我們想象一下我的XAML看起來像這樣:問題從預覽處理程序WPF命令,而不是陷入循環

<UserControl.CommandBindings> 
    <CommandBinding Command="ApplicationCommands.Delete" Executed="CommandBinding_DeleteExecuted" PreviewExecuted="CommandBinding_PreviewDeleteExecuted"/> 
</UserControl.CommandBindings> 

而且我有C#代碼看起來像這樣:

private void CommandBinding_DeleteExecuted(object sender, ExecutedRoutedEventArgs e) 
{ 

} 

private void CommandBinding_PreviewDeleteExecuted(object sender, ExecutedRoutedEventArgs e) 
{ 
    //Would like to invoke Delete command from here 
} 

我想要做的是讓我的預覽處理程序被調用並執行一些自定義檢查。如果自定義檢查通過,那麼我希望再次從預覽處理程序中調用delete命令(或者,如果我可以讓原始命令'通過'我的預覽和執行處理程序,那麼這將非常棒) 。因此,在這一點上,當我重新發出刪除命令時,不再涉及到其他XAML。

如果我以某種方式從我的預覽處理程序重新發出刪除命令,我想它會導致再次調用預覽處理程序(無限循環)。相反,我希望重新發布的命令忽略我的預覽和執行處理程序,並讓任何刪除命令處理程序在樹中進一步處理刪除命令。

有沒有辦法做到這一點?

+0

不知道你在這裏需要什麼。那麼,如果您的自定義檢查通過,您不希望被調用的處理程序被調用?相反,你想讓它在樹上的其他命令上調用? 如果命令沒有通過,你希望它被調用? – 2010-07-30 17:11:26

+0

如果自定義檢查失敗。那麼我不希望執行的處理程序被調用;而沒有任何反應。如果自定義檢查成功,那麼我想調用該命令,就好像我的預執行處理程序不在位。 – Notre 2010-07-30 21:04:40

回答

0

我有基於另一個question的解決方案,這似乎是好工作:

private void CommandBinding_PreviewDeleteExecuted(object sender, ExecutedRoutedEventArgs e) 
    { 
     bool ignoreDeleteCommand = DoSomeTest(); 


     if (!ignoreDeleteCommand) 
     { 
      foreach (CommandBinding cb in CommandBindings) 
      { 
       if (cb.Command.Equals(ApplicationCommands.Delete)) 
       { 
        //Unsubscribe from this handler, invoke the Delete command (which will be handled by child) and then 
        //resubscribe to this handler 
        cb.PreviewExecuted -= new ExecutedRoutedEventHandler(CommandBinding_PreviewDeleteExecuted); 
        cb.Command.Execute(null); 
        cb.PreviewExecuted += new ExecutedRoutedEventHandler(CommandBinding_PreviewDeleteExecuted); 
       } 
      } 
     } 
    } 
0

沒有 - 命令處理程序將始終最終首先觸擊父項;如果你想將一個命令代理給另一個命令,他們必須有不同的名字。