首页 > 解决方案 > 从 MainWindow.xaml.cs 调用 ShowWindowCommand()

问题描述

我想从我的 MainWindow() 中调用函数 ShowWindowCommand() 和 HideWindowCommand()。

我有以下课程:

public class NotifyIconViewModel
{
    public ICommand ShowWindowCommand
    {
        get
        {
            return new DelegateCommand
            {
                CanExecuteFunc = () => Application.Current.MainWindow == null,
                CommandAction = () =>
                {
                    Application.Current.MainWindow = new WorkingTimer.MainWindow();
                    Application.Current.MainWindow.Show();
                }
            };
        }
    }

    public ICommand HideWindowCommand
    {
        get
        {
            return new DelegateCommand
            {
                CommandAction = () => Application.Current.MainWindow.Close(),
                CanExecuteFunc = () => Application.Current.MainWindow != null
            };
        }
    }

通常,从 NotifyIconRessource.xaml 中的上下文菜单调用 ShowWindowCommand() 和 HideWindowsCommand()

<ContextMenu x:Shared="false" x:Key="SysTrayMenu">
        <MenuItem Header="Show Window" Command="{Binding ShowWindowCommand}"/>
        <MenuItem Header="Hide Window" Command="{Binding HideWindowCommand}"/>
        <Separator />
        <MenuItem Header="Reset Timer" Command="{Binding ResetTimerCommand}"/>
        <Separator />
        <MenuItem Header="Exit" Command="{Binding ExitApplicationCommand}" />
    </ContextMenu>

我怎样才能做到这一点 ?

标签: c#

解决方案


您首先必须创建该类的公共属性,然后将其设置为视图的数据上下文:

public NotifyIconViewModel NotifyIconVM { get; set; }

MainWindow() 
{ 
    InitializeComponent();
    NotifyIconVM = new NotifyIconViewModel();
    DataContext = NotifyIconVM;
}

设置数据上下文将告诉视图在哪里查找命令。


推荐阅读