index > Windows Presentation Foundation ("Avalon") > Menu items disabled when setting a command

Menu items disabled when setting a command

When I change this:

        <MenuItem InputGestureText="Ctrl+N">
          <MenuItem.Header>
            <AccessText>_New</AccessText>
          </MenuItem.Header>
        </MenuItem>

into this:

        <MenuItem Command="New" InputGestureText="Ctrl+N">
          <MenuItem.Header>
            <AccessText>_New</AccessText>
          </MenuItem.Header>
        </MenuItem>

The MenuItem appears disabled. At first I thought it was the CommandBinding so I even wired up a CanExecute method but to no avail...

Does anybody know what's going on?

 

Thanks!

By the way IsEnabled="True" doesn't help either.

Erno de Weerd
Command= needs to have a Command object as its value, not an arbitrary string.  There are system static classes like ApplicationCommands and others that have various commands as static fields.  I think you want command="ApplicationCommands.New".


Michael (MVP C# / WPF)
MichaelLatta

Thanks for answering but unfortunately it's not the solution. I know that I can not assign *some* string. If I state *some* string I get a runtime error. So it must know New (and also accepts "ApplicationCommands.New")

Thanks

 

Erno de Weerd

A control which is attached to a command will be disabled if that command cannot be executed.  Take the Application.Cut command for example.  If the target of the command is a TextBox (which has built in support for the cut command) and there is no text selected, the control which executes the cut command will not be enabled, but if there is text selected the control is enabled. 

 

You can see the same behavior in the edit context menu of Word, for example.  If there is no text selected, the Cut context menuitem is disabled, but when there is text selected, the cut context menuitem is enabled.

 

Many controls have built in logic for some of the predefined commands, such as the TextBox control which supports copy, cut, paste, undo, redo.  But other controls (or custom controls) may not have built in support so you??l have to add the command logic. 

 

In your example you may just need to explicitly add a CommandTarget to the MenuItem.  For example,

      <MenuItem Command="ApplicationCommands.Copy"

                       CommandTarget="{Binding ElementName=TxtBox1}">

 

Defines the CommandTarget of the command to an instance of a TextBox control Named TxtBox1 

 

If there is not a CommandTarget defined, the control with focus will be set to the CommandTarget.

 

Probably though there is not an Executed or a CanExecute method bound to the command. The CanExecute method returns false if the command can not be executed, which in turn disables the control.  Try wiring up an Executed method and an CanExecute method in the CommandBinding.  Next you??l want to create the Executed and CanExecute methods in code behind.  

XAML Code: (you can place this CommandBinding on the Menu itself or grandparent of the menuitem, but I like to put all the CommandBindings I can on the main Window element.  RoutedCommands act like input events and bubble or tunnel up the UI tree, so as long as the binding is a parent, it will be executed.  Keep in mind though, if there are multiple bindings for the command only the first one hit will be applied)

<Window> 

    <Window.CommandBindings>  

         <CommandBinding Executed=??ewExecute??CanExecute=?OnQuery??/>

     </Window.CommandBindings>    

      . . .

      <MenuItem Command="New" InputGestureText="Ctrl+N">
          <MenuItem.Header>
            <AccessText>_New</AccessText>
          </MenuItem.Header>
        </MenuItem>
 

In Code Behind

        public void NewExecute(object sender, ExecutedRoutedEventArgs e)

        {

           // place Command execute logic here

        }

        public void OnQuery(object sender, CanExecuteRoutedEventArgs e)

        {

           // place whatever logic you want to insure that the execute is valid for your scenario

            e.CanExecute = true;

        }

I hope this helps.


Brian




Brian Love [MSFT] This posting is provided "AS IS" with no warranties, and confers no rights.
Brian Love

I left out the part of the CommandBinding

   <Window.CommandBindings>  

         <CommandBinding Command="New" Executed=??ewExecute??CanExecute=?OnQuery??/>

     </Window.CommandBindings>   

 

 

 




Brian Love [MSFT] This posting is provided "AS IS" with no warranties, and confers no rights.
Brian Love

Hmmm... ok this works. But I'm am curious why my code didn't work because I did the same thing but from within code:

        public MainWindow()
        {
            InitializeComponent();

            CommandBinding cmd;
            cmd = new CommandBinding(ApplicationCommands.New, new ExecutedRoutedEventHandler(CommandNew_Executed), new CanExecuteRoutedEventHandler(Command_CanExecute));
        }

Is this the wrong place/moment to do this?

 

Thanks!

Erno de Weerd

That code looks correct.  All you need to do now is add the CommandBinding to the UIElement you want it attached to. RoutedCommands are essentially input events and are routed up and down the UI tree, so the CommandBinding needs to be associated with a UIElement in order for it to be applied.

If you are defining the main window in XAML, you can give it a name and then reference that name in the code behind. 

XAML:

<Window . . .

                Name="MyWIndow">

</Window>

Code Behind:

       public MainWindow()
        {
            InitializeComponent();

            CommandBinding cmd;
            cmd = new CommandBinding(ApplicationCommands.New, new ExecutedRoutedEventHandler(CommandNew_Executed), new CanExecuteRoutedEventHandler(Command_CanExecute));
           

            MyWindow.CommandBindings.Add(cmd);

 }

 




Brian Love [MSFT] This posting is provided "AS IS" with no warranties, and confers no rights.
Brian Love

Arg! That's it! I forgot the MyWindow.CommandBindings.Add(cmd);

Thank you so much!

BTW: instead of MyWindow I simply use this

Erno de Weerd
I had this same problem but I had the CommandBindings hooked up correctly it was just that I had to e
Corbin Hoenes

Anybody knows what's the expected behavior when press key combination: "Ctrl+N"?

If I add event handler, "NewClicked", Ctrl+N won't find the event, anybody know why?

<MenuItem InputGestureText="Ctrl+N" Click="NewClicked">
<MenuItem.Header>
<AccessText>_New</AccessText>
</MenuItem.Header>
</MenuItem>

Thanks




Donald
Donald_La
reply 10

You can use google to search for other answers

 

More Articles

• ToolBar - OverflowGrid style?
• Sharing ControlTemplate
• How To: Attach event handler to element in DataTemplate?
• Vertical lines in the GridView
• Feature lag: Binding ConverterParameter
• gridview
• OnMediaEnded and weird MediaElement.Play behavior
• STA error when creating scrollviewer in background thread?
• Forms , XAML , Events
• Cannot re-initialize ResourceDictionary instance. Error at object...
Bookmark and Share
Welcome to Bokebb   New Update  
 

New Articles

• frameworkelementfactory grid columndefin
• Dock Panel System
• XAML - its purpose
• How can I make a mouseOver also cause a
• Will WPF *EVER* work under W2K?
• Measure distance to an item inside a sta
• Using Styles in WPF
• Synchronizing animation to video
• ListBox item scroll animation
• Stretching Frame Content
• Resource Dictionary "Adding Stroke/
• Repeating controls
• Printing WindowsFormsHost
• Textblock/Label/Frame/RichTextBox/Whatev
• Access a control in datatemplate of a Li

Hot Articles

• Change Source of Frame to display differ
• Pagination With Xaml(XBAP)
• Possible Bug.... WPF throws excpetion wh
• The best way to draw RGB array in WPF
• Floating UI Elements in a FlowDocument
• Can't get to original source from Execut
• WPF Program Managers
• Problem with MergedDictionaries and Elem
• XAML RSS Reader problem
• Customizing WPF DataTemplates....
• Problem for report Viewer
• Setting foreground and background to be
• How to base width calculation on presenc
• Binding to Combobox.Text when IsSynchron
• GetPositionFromPoint causes object refer

Recommend Articles

• ClickOnce Installation
• How can i define string tables in WPF pr
• How to get the screen resolution in wpf
• Problem Animating Background in Style fo
• Code formatting on Forum
• XamlWriter, MarkupObject How to ?
• Possible bug: Hyperlink in a ListBox doe
• problem using custom control library!!!
• The best way to draw RGB array in WPF
• getting the june ctp
• Triggers on TreeViewItems and escaping t
• MenuItem DataTrigger error trying to cha
• Regarding to Report Viewer
• How to create irregular window from PNG
• Cannot set Name attribute value 'Tab1' o