我正在使用WPF NotifyIcon,实际上我正在尝试学习如何在将托盘中的窗口最小化后显示窗口。因此,当用户双击图标时,窗口应再次出现。实际上,我已经创建了以下代码:

private void MetroWindow_StateChanged(object sender, EventArgs e)
{
   TaskbarIcon tbi = new TaskbarIcon();
   tbi.DoubleClickCommand = Recover(tbi);

     switch (WindowState)
     {
         case WindowState.Minimized:
            Visibility = Visibility.Hidden;
            tbi.Visibility = Visibility.Visible;
            break;
     }
}

private void Recover(TaskbarIcon tbi)
{
    tbi.Visibility = Visibility.Hidden;
    Visibility = Visibility.Visible;
}


当我最小化窗口时如何看到托盘中的图标。这个工作很好。我已经声明了这样的图标:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:local="clr-namespace:Test.Utils.Resources.UIDictionary"
                xmlns:tb="http://www.hardcodet.net/taskbar">

<tb:TaskbarIcon x:Key="NotifyIcon"
              IconSource="/Utils/Images/Test.ico"
              ToolTipText="hello world" />

</ResourceDictionary>


现在的问题是,在此行上:tbi.DoubleClickCommand = Recover(tbi);我收到此错误:


  无法在System.Windows.Input.ICommand中将类型转换为void


不可能以这种方式调用方法吗?为什么?

最佳答案

这是您需要的简单RelayCommand的代码

public class RelayCommand : ICommand
{
    private Action<object> action;
    public RelayCommand(Action<object> action)
    {
        this.action = action;
    }
    public bool CanExecute(object parameter)
    {
        return true;
    }

    public void Execute(object parameter)
    {
        action(parameter);
    }

    public event EventHandler CanExecuteChanged;
}


然后,像其他答案一样

tbi.DoubleClickCommand =new RelayCommand(_ => Recover(tbi));

08-19 15:22