How to access a command from the MainWindow level in another window?

I am trying to access the commands that are defined in MainWindow.xaml in another window. I can get the gray headers of these commands. I wonder what needs to be done to get full access.

Command example:

public partial class MainWindow : Window
{
    public static RoutedUICommand AddCommand1 = new RoutedUICommand("Command ", "command1", typeof(MainWindow));

    public MainWindow()
    {
        InitializeComponent();
        this.CommandBindings.Add(new CommandBinding(AddCommand1, AddCommand1Executed));
    }

    private void AddCommand1Executed(object sender, ExecutedRoutedEventArgs e)
    {
        AddNewItem picker = new AddNewItem();
        picker.ShowDialog();
    }

I access this style command through data binding:

<Menu x:Name="TaskMenuContainer"><MenuItem x:Name="menuItem" Header="TASKS" ItemsSource="{Binding}" Template="{DynamicResource TaskMenuTopLevelHeaderTemplateKey}">
<MenuItem.ItemContainerStyle>
    <Style TargetType="{x:Type MenuItem}">
        <Setter Property="Command" Value="{Binding}" />
        <Setter Property="Header" Value="{Binding Text, RelativeSource={RelativeSource Self}}" />
        <Setter Property="CommandTarget" Value="{Binding RelativeSource={RelativeSource Self}}"/>
    </Style>
</MenuItem.ItemContainerStyle>

These commands work on pages loaded inside MainWindow.xaml through a frame. However, if I have a popup that is not part of MainWindow.xaml, these commands are only grayed out and no longer work (cannot be executed). Any advice is appreciated!

+3
source share
1 answer

, . , CommandManager.RegisterClassCommandBinding:

:

public static class GlobalCommands
{
    public static RoutedUICommand AddCommand1 = new RoutedUICommand("Command ", "command1", typeof(MainWindow));
}

, , :

public partial class MainWindow : Window
{
    static MainWindow()
    {
       CommandManager.RegisterClassCommandBinding(typeof(Window), new CommandBinding(GlobalCommands.AddCommand1, AddCommand1Executed, CanAddExecute));
    }

    private static void AddCommand1Executed(object sender, ExecutedRoutedEventArgs e)
    {
        AddNewItem picker = new AddNewItem();
        picker.ShowDialog();
    }
}

x:Static:

<Setter Property="Command" Value="{x:Static my:GlobalCommands.AddCommand1}" />


, , . , .

, Window, Window, .

Window, . - , , . .

+3

Source: https://habr.com/ru/post/1791076/