Search code examples
c#wpfcommandcommandbinding

CommandBinding relative path


Within my window (let's say MyCanvas) there's a new command definition which I then bind to my window. Usually the handlers for CanExecute and Executed are directly within MyCanvas. But is it somehow possible to bind the CanExecute and Executed handlers to a relative path like for example MyCanvas.Logic.CanExecute_OpenCamera?

This is my current XAML.

<Window.Resources>
        <RoutedUICommand x:Key="OpenCamera" Text="Open camera" />
</Window.Resources>    
<Window.CommandBindings>
    <CommandBinding Command="{StaticResource OpenCamera}" CanExecute="CanExecute_OpenCamera" Executed="Executed_OpenCamera"/>
</Window.CommandBindings>

This is what I'm trying to define. Logic is public property of MyCanvas.

<Window.Resources>
        <RoutedUICommand x:Key="OpenCamera" Text="Open camera" />
</Window.Resources>    
<Window.CommandBindings>
    <CommandBinding Command="{StaticResource OpenCamera}" CanExecute="Logic.CanExecute_OpenCamera" Executed="Logic.Executed_OpenCamera"/>
</Window.CommandBindings>

Solution

  • You can, but you have to use converters which create delegates to the respective methods from a bound object of the class, or from its type, if the methods are static. See http://wpfglue.wordpress.com/2012/05/07/commanding-binding-controls-to-methods/ for details.