Why is this WPF RoutedCommand bound Context MenuItem disabled?

前端 未结 5 2075
北恋
北恋 2020-12-19 06:46

I\'m still fumbling my way around WPF at the moment, and can not figure out why this context menu item is disabled:



        
5条回答
  •  生来不讨喜
    2020-12-19 07:42

    here is the general pattern that I use....

    first, keep your commands in thier own static class, this promotes reuse,etc....

    public static class MyCommands
    {
        public static RoutedUICommand CmdFoo = new RoutedUICommand("CmdFoo", 
                                                                   "CmdFoo", 
                                                                   typeof(MyCommands));
    }
    

    second, register the command in the control/window/etc. you want to use it in, normally in the constructor

    public MyControl
    {
        public MyControl()
        {
            CommandBindings.Add( 
                new CommandBinding( MyCommands.CmdFoo,   // this is the command object
                                    XCutFooCommand,      // execute
                                    CanXCuteFooCommand));// can execute?
        }
    

    third, create your handlers in the control/window/etc.....

      public void CanExecuteRerollCommand(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;  // can this command be executed?
            e.Handled = true;     // has this event been handled?
        }
        public void ExecuteRerollCommand(object sender, ExecutedRoutedEventArgs e)
        {
        // do stuff
        }
    }
    

    lastly, your xaml ought to look like this:

        
            
                
            
            
        
    

    notice that there is no binding. Also, notice the in the . here is a reference.... http://www.wiredprairie.us/journal/2007/04/commandtarget_menuitem_context.html

    the command being disabled is addressed at this site

提交回复
热议问题