There is xaml

<local:TestWindowA x:Class="TestEther.TestWindow" ****** DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}"> <local:TestWindowA.Menu> <Menu> <MenuItem Header="File"> <MenuItem Command="{Binding Path=Comm}" CommandManager.Executed="MenuItem_Executed" CommandManager.CanExecute="MenuItem_CanExecute"/> </MenuItem> </Menu> </local:TestWindowA.Menu> </local:TestWindowA> 

Here is the code

 public partial class TestWindow : TestWindowA { private RoutedUICommand _comm; public RoutedUICommand Comm { get { return _comm; } set { _comm = value; } } public TestWindow() { Comm = new RoutedUICommand("Comm", "comm", GetType()); //Comm = new RoutedUICommand("Comm", "comm", typeof(EtherTabControl)); InitializeComponent(); } private void MenuItem_Executed(object sender, ExecutedRoutedEventArgs e) { Console.WriteLine("comm"); } private void MenuItem_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = true; } } 

When I start, I open the menu and see "Comm" there. I click on it, "comm" is displayed in the console. So it was intended.

The problem is that when I translate the focus to other window elements, the command is no longer active, although MenuItem_CanExecute is running and it sets e.CanExecute = true;

  • And why are you doing something strange, through the CommandManager.Executed and CommandManager.CanExecute ? Usually done via CommandBinding . - VladD
  • @VladD, as found and did) Now I read about the binding - iRumba
  • @VladD, I found the info on MSDN, but the example there, as usual, is not very. It will be easier to understand if you give an example with the implementation of the task I proposed. I will mark this as an answer. - iRumba
  • @VladD, this construction does not work <CommandBinding Command="{Binding Comm}" CanExecute="MenuItem_CanExecute" Executed="MenuItem_Executed"/> , because Binding cannot be specified in Command. It turns out that I can only use the already predefined commands? - iRumba
  • @VladD, everything worked out, thanks. I added <RoutedUICommand Text="Comm" x:Key="comm"/> to the resources of the window and use it through the StaticResource . If issue, I will mark as the answer. :) - iRumba

0