|
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. |