views:

367

answers:

2

Hi,

I a have 2 distinct UI elements in distinct files : a menuItem (in window.xaml) and a userControl (in foo.xaml).

Both have exactly the same logic : they are enabled only if a condition is matched and call the same method. To code this logic, i use RoutedCommands.

I could use 2 different RoutedCommands in each file with same condition in the CanExecute and Executed. It works.

I would like to improve the code to follow the D.R.Y. rule and externalize the routedCommand and the attached methods. This is the binding in both files :

<CommandBinding Command="{x:Static RoutedCommands:TestRoutedCommand.test}"
                    Executed="RoutedCommands:TestRoutedCommand.OnTest"
                    CanExecute="RoutedCommands:TestRoutedCommand.CanTest" />

this is TestRoutedCmmand.cs :

public class TestRoutedCommand
{
    public static RoutedCommand test = new RoutedCommand();

    public static void OnTest(object sender, ExecutedRoutedEventArgs e)
    {
        System.Windows.MessageBox.Show("test -on");
    }

    public static void CanTest(object sender, CanExecuteRoutedEventArgs e)
    {
        System.Windows.MessageBox.Show("test -can");

        e.CanExecute = true;
    }
}

When I do that, the compiler report this error :

Error   1 unknown generation error, 'MC6005 :        
Executed="RoutedCommands:TestRoutedCommand.OnTest" is not valid.  
'RoutedCommands:TestRoutedCommand.OnTest' is not a valid name for an event handler method. 
Only instance methods of the generated class or code-behind are valid

(The translation may not be exact because the original message was not in English)

It seems that external methods are not supported, but i would be sure i did not miss something. I wonder if it is the fact that my methods are static ?

Is there another way to externalize my methods or do i have to stay with these 4 methods calling only 2 others ?

Note : in my project this is more 30 duplicated routedCommand methods callings only 2 others... this is why it bother me so much.

Thanks.

+1  A: 

Presumably your RoutedCommand is a static member on a class (for example, Commands). You need to pass that static member into the Command property:

<CommandBinding Command="{x:Static local:Commands.TestCommand}"
                    Executed="RoutedCommands.TestRoutedCommand.OnTest"
                    CanExecute="RoutedCommands.TestRoutedCommand.CanTest" />

HTH, Kent

Kent Boogaart
Indeed, i forgot the x:Static... Thanks, but this doesn't solve my issue. I edited my question to correct this and to be more precise.
rockeye
A: 

I answer myself :

As the compiler does not accept extern delegates with RoutedCommand, the best practice is to use a custom implementation of ICommand like these. No more CommandBinding is required and the problem is solved!

rockeye