WPF: Problem with taking command handlers out of code behind
I have some command binding defined in my XAML:
<UserControl.CommandBindings> <CommandBinding Command="commands:Commands.GrantAccessCommand" Executed="HelpExecuted" /> </UserControl.CommandBindings>
So GrantAccessCommand is located in a seperate class called Commands and HelpExecuted is in my code behind. It works fine. Now when I put HelpExecuted in the other class as well I get an error "...HelpExecuted' is not a valid event handler method name. Only instance methods on the generated or code-behind class are valid." The code:
Executed="commands:Commands.HelpExecuted" //I also tryed: Executed="x:Static commands:Commands.HelpExecuted"
I know I can do this in code behind using CommandBindings.Add(new CommandBinding(GrantAccessCommand, HelpExecuted)); But I want to do this using XAML
Is there a way?
My guess is .Net 3.5. From http://www.codeproject.com/KB/WPF/CentralizingWPFCommands.aspx: The current WPF version's XAML does not allow us to bind event handlers in this way. The event handlers must be defined in the code-behind file inside the MainWindow class. I don't know if this is a bug, an accidentally left out feature, or if we are not even supposed to use this functionality, but this stops us from defining a centralized location for handling all commands' Executed and CanExecute events.
The workaround is to define bindings in code:
window.CommandBindings.Add(new CommandBinding(Help, HelpExecuted, HelpCanExecute));