安装Nuget包
Install-Package Hardcodet.NotifyIcon.Wpf
App.xaml添加:
<Application
x:Class="ToDoList.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:cg2="clr-namespace:CgdataBase"
xmlns:cvt="clr-namespace:CgdataBase.Converters;assembly=CgdataBase.WPF"
xmlns:local="clr-namespace:ToDoList"
xmlns:tb="http://www.hardcodet.net/taskbar"
xmlns:vm="clr-namespace:ToDoList.ViewModels">
<Application.Resources>
<ResourceDictionary>
<ContextMenu x:Key="SysTrayMenu" x:Shared="false">
<MenuItem Command="{Binding ExitApplicationCommand}" Header="退出" />
</ContextMenu>
<tb:TaskbarIcon
x:Key="Taskbar"
ContextMenu="{StaticResource SysTrayMenu}"
DoubleClickCommand="{Binding ShowWindowCommand}"
IconSource="App.ico"
ToolTipText="ToDoList">
<tb:TaskbarIcon.DataContext>
<vm:NotifyIconViewModel />
</tb:TaskbarIcon.DataContext>
</tb:TaskbarIcon>
</ResourceDictionary>
</Application.Resources>
</Application>
App.xaml.cs添加:
using Hardcodet.Wpf.TaskbarNotification;
using System.Windows;
namespace ToDoList
{
public partial class App : Application
{
private TaskbarIcon _taskbar;
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
_taskbar = (TaskbarIcon)FindResource("Taskbar");
}
}
}
NotifyIconViewModel.cs文件
using Prism.Commands;
using Prism.Mvvm;
namespace ToDoList.ViewModels
{
public class NotifyIconViewModel : BindableBase
{
public DelegateCommand ShowWindowCommand { get; private set; }
public DelegateCommand ExitApplicationCommand { get; private set; }
public NotifyIconViewModel()
{
ShowWindowCommand = new DelegateCommand(OnShowWindow);
ExitApplicationCommand = new DelegateCommand(OnExitApplication);
}
private void OnShowWindow()
{
//显示主窗体
}
private void OnExitApplication()
{
//退出应用
}
}
}