简体   繁体   English

无法将void转换为ICommand

[英]Cannot convert void to ICommand

I'm using WPF NotifyIcon , and actually I'm trying to learn how to display the window after minimize it in the tray. 我正在使用WPF NotifyIcon ,实际上我正在尝试学习如何在托盘中最小化窗口后显示窗口。 So when the user double click on the icon, the window should appear again. 因此,当用户双击图标时,窗口应再次出现。 Actually I've created this code: 实际上,我已经创建了以下代码:

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;
}

How you can see when I minimize the window the icon in the tray appear. 当我最小化窗口时如何看到托盘中的图标。 This working pretty well. 这个工作很好。 I've declared the icon like this: 我已经声明了这样的图标:

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

Now the problem is that on this line: tbi.DoubleClickCommand = Recover(tbi); 现在的问题是,在此行上: tbi.DoubleClickCommand = Recover(tbi); I get this error: 我收到此错误:

Cannot convert the type void in System.Windows.Input.ICommand 无法在System.Windows.Input.ICommand中将类型转换为void

It's not possible call a method in this way? 不可能以这种方式调用方法吗? Why? 为什么?

Here is the code for a simple RelayCommand that is what you need 这是您需要的简单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;
}

and then, like the other answer its just 然后,像其他答案一样

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

Actually, DoubleClickCommand is of type ICommand . 实际上, DoubleClickCommand的类型为ICommand

You need to set it as RelayCommand which is subtype of ICommand for it to compile like: 您需要将其设置为ICommand子类型RelayCommand ,以便像这样进行编译:

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

You can read more about Relay Commands on this MSDN link 您可以在此MSDN链接上阅读有关中继命令的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM