创建交互式通知:ToastNotifications自定义消息组件开发指南
创建交互式通知ToastNotifications自定义消息组件开发指南【免费下载链接】ToastNotificationsToast notifications for WPF allows you to create and display rich notifications in WPF applications. Its highly configurable with set of built-in options like positions, behaviours, themes and many others. Its extendable, it gives you possibility to create custom and interactive notifications in simply manner.项目地址: https://gitcode.com/gh_mirrors/to/ToastNotificationsToastNotifications是WPF应用程序中创建和显示丰富通知的终极解决方案这个强大的通知库提供了高度可配置的选项包括位置、行为、主题等内置功能。更重要的是它具备出色的扩展性让开发者能够以简单的方式创建自定义和交互式通知组件。本文将为您提供完整的自定义消息组件开发指南帮助您掌握ToastNotifications的核心功能。 为什么选择ToastNotificationsToastNotifications v2采用插件化架构核心库专注于通知的创建和显示机制而预定义消息和其他非核心功能则由独立的NuGet包提供。这种设计让您可以根据需求灵活选择功能模块同时保持代码的简洁性。核心优势高度可配置支持多种位置、行为和主题选项易于扩展轻松创建自定义通知组件交互性强支持按钮、输入框等交互元素性能优化高效的显示和生命周期管理 快速开始安装与基础配置一键安装步骤首先通过NuGet安装ToastNotifications核心包Install-Package ToastNotifications如果您需要预定义的消息类型错误、信息、警告、成功可以同时安装消息包Install-Package ToastNotifications.Messages基础配置方法在App.xaml中导入ToastNotifications.Messages主题Application.Resources ResourceDictionary ResourceDictionary.MergedDictionaries ResourceDictionary Sourcepack://application:,,,/ToastNotifications.Messages;component/Themes/Default.xaml / /ResourceDictionary.MergedDictionaries /ResourceDictionary /Application.Resources创建Notifier实例的完整配置示例using ToastNotifications; using ToastNotifications.Lifetime; using ToastNotifications.Position; Notifier notifier new Notifier(cfg { cfg.PositionProvider new WindowPositionProvider( parentWindow: Application.Current.MainWindow, corner: Corner.TopRight, offsetX: 10, offsetY: 10); cfg.LifetimeSupervisor new TimeAndCountBasedLifetimeSupervisor( notificationLifetime: TimeSpan.FromSeconds(3), maximumNotificationCount: MaximumNotificationCount.FromCount(5)); cfg.Dispatcher Application.Current.Dispatcher; }); 创建自定义通知组件自定义通知类设计创建自定义通知需要两个核心组件通知数据类包含要显示的数据和显示部件描述通知的外观。步骤1创建CustomNotification类这个类继承自NotificationBase并实现INotifyPropertyChanged接口using System.ComponentModel; using System.Runtime.CompilerServices; using ToastNotifications.Core; public class CustomNotification : NotificationBase, INotifyPropertyChanged { private CustomDisplayPart _displayPart; public override NotificationDisplayPart DisplayPart _displayPart ?? (_displayPart new CustomDisplayPart(this)); public CustomNotification(string message) { Message message; } private string _message; public string Message { get { return _message; } set { _message value; OnPropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName]string propertyName null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }步骤2创建显示部件DisplayPart显示部件是描述通知外观的WPF用户控件。创建CustomDisplayPart.xaml文件core:NotificationDisplayPart x:ClassYourNamespace.CustomDisplayPart xmlnshttp://schemas.microsoft.com/winfx/2006/xaml/presentation xmlns:xhttp://schemas.microsoft.com/winfx/2006/xaml xmlns:mchttp://schemas.openxmlformats.org/markup-compatibility/2006 xmlns:dhttp://schemas.microsoft.com/expression/blend/2008 xmlns:coreclr-namespace:ToastNotifications.Core;assemblyToastNotifications mc:Ignorabled Background#FF2D2D30 d:DesignHeight80 d:DesignWidth300 d:DataContext{d:DesignInstance local:CustomNotification, IsDesignTimeCreatableFalse} Border BorderBrush#FF007ACC BorderThickness2 CornerRadius5 Grid Margin10 Grid.RowDefinitions RowDefinition HeightAuto/ RowDefinition Height*/ /Grid.RowDefinitions TextBlock Text自定义通知 FontWeightBold FontSize14 ForegroundWhite Margin0,0,0,5/ TextBlock Grid.Row1 Text{Binding Message} FontWeightLight ForegroundWhite TextWrappingWrap / /Grid /Border /core:NotificationDisplayPart对应的代码文件CustomDisplayPart.xaml.cspublic partial class CustomDisplayPart : NotificationDisplayPart { public CustomDisplayPart(CustomNotification customNotification) { InitializeComponent(); Bind(customNotification); } } 高级配置选项通知位置配置ToastNotifications提供三种内置位置提供器WindowPositionProvider- 通知跟随指定窗口位置PrimaryScreenPositionProvider- 通知始终显示在主屏幕指定位置ControlPositionProvider- 通知跟随指定UI控件位置// 窗口位置提供器示例 cfg.PositionProvider new WindowPositionProvider( parentWindow: Application.Current.MainWindow, corner: Corner.TopRight, offsetX: 10, offsetY: 10); // 主屏幕位置提供器示例 cfg.PositionProvider new PrimaryScreenPositionProvider( corner: Corner.BottomRight, offsetX: 10, offsetY: 10);通知生命周期管理使用LifetimeSupervisor选项控制通知何时消失// 基于时间的生命周期管理 cfg.LifetimeSupervisor new TimeAndCountBasedLifetimeSupervisor( notificationLifetime: TimeSpan.FromSeconds(3), maximumNotificationCount: MaximumNotificationCount.FromCount(5)); // 基于数量的生命周期管理 cfg.LifetimeSupervisor new CountBasedLifetimeSupervisor( maximumNotificationCount: MaximumNotificationCount.UnlimitedNotifications());消息选项配置ToastNotifications支持丰富的消息选项var options new MessageOptions { FontSize 30, // 设置通知字体大小 ShowCloseButton false, // 显示/隐藏关闭按钮 Tag 自定义标签, // 用于回调的标签 FreezeOnMouseEnter true, // 鼠标悬停时暂停自动消失 NotificationClickAction n // 通知点击回调 { n.Close(); // 关闭通知 notifier.ShowSuccess(已点击); }, CloseClickAction n // 关闭按钮点击回调 { var opts n.DisplayPart.GetOptions(); ShowInformation($关闭按钮被点击标签{opts.Tag}); } }; 创建交互式通知添加按钮交互功能创建支持按钮交互的自定义通知public class InteractiveNotification : NotificationBase, INotifyPropertyChanged { public ICommand ConfirmCommand { get; } public ICommand CancelCommand { get; } public InteractiveNotification(string message, Action confirmAction, Action cancelAction) { Message message; ConfirmCommand new RelayCommand(confirmAction); CancelCommand new RelayCommand(cancelAction); } // 其他属性... }在XAML中添加按钮StackPanel OrientationHorizontal HorizontalAlignmentRight Margin0,10,0,0 Button Content确认 Command{Binding ConfirmCommand} Margin0,0,10,0 Padding10,5/ Button Content取消 Command{Binding CancelCommand} Padding10,5/ /StackPanel添加输入框功能创建支持用户输入的自定义通知public class InputNotification : NotificationBase, INotifyPropertyChanged { private string _inputText; public string InputText { get { return _inputText; } set { _inputText value; OnPropertyChanged(); } } public ICommand SubmitCommand { get; } public InputNotification(Actionstring submitAction) { SubmitCommand new RelayCommand(() submitAction(InputText)); } } 项目文件结构参考了解ToastNotifications的项目结构有助于更好地进行自定义开发核心库结构Src/ToastNotifications/Core/- 核心接口和基类Src/ToastNotifications/Display/- 显示相关组件Src/ToastNotifications/Lifetime/- 生命周期管理Src/ToastNotifications/Position/- 位置提供器消息库结构Src/ToastNotifications.Messages/Core/- 消息基类Src/ToastNotifications.Messages/Error/- 错误消息Src/ToastNotifications.Messages/Information/- 信息消息Src/ToastNotifications.Messages/Success/- 成功消息Src/ToastNotifications.Messages/Warning/- 警告消息示例项目Src/Examples/BasicUsageExample/- 基础使用示例Src/Examples/ConfigurationExample/- 配置示例Src/Examples/CustomNotificationsExample/- 自定义通知示例️ 最佳实践与调试技巧1. 使用扩展方法简化调用创建扩展方法让自定义通知的使用更加简洁public static class CustomMessageExtensions { public static void ShowCustomMessage(this Notifier notifier, string message) { notifier.NotifyCustomNotification(() new CustomNotification(message)); } public static void ShowInteractiveMessage(this Notifier notifier, string message, Action confirmAction, Action cancelAction) { notifier.NotifyInteractiveNotification(() new InteractiveNotification(message, confirmAction, cancelAction)); } } // 使用方式 notifier.ShowCustomMessage(这是一个自定义通知);2. 处理键盘事件默认情况下ToastNotifications会阻止所有键盘输入。如果需要文本输入功能需要配置键盘事件处理器cfg.KeyboardEventHandler new AllowedSourcesInputEventHandler( new []{ typeof(CustomInputDisplayPart) });3. 清理通知ToastNotifications提供多种清理通知的方式notifier.ClearMessages(new ClearAll()); // 清除所有通知 notifier.ClearMessages(new ClearByMessage()); // 清除指定消息的通知 notifier.ClearMessages(new ClearByTag()); // 清除指定标签的通知 notifier.ClearMessages(new ClearFirst()); // 清除第一个通知 notifier.ClearMessages(new ClearLast()); // 清除最后一个通知4. 显示选项配置cfg.DisplayOptions.TopMost true; // 设置通知显示在最顶层 cfg.DisplayOptions.Width 250; // 设置通知宽度 实用技巧与常见问题性能优化建议合理设置通知数量使用MaximumNotificationCount限制同时显示的通知数量优化动画效果自定义通知动画时注意性能影响及时释放资源不再使用Notifier时调用Dispose()方法常见问题解决问题1通知不显示检查Dispatcher是否正确设置确认PositionProvider配置正确验证消息是否成功创建问题2通知位置不正确检查父窗口或控件引用确认Corner和Offset参数验证屏幕DPI设置问题3交互功能失效检查命令绑定是否正确确认事件处理器已注册验证数据绑定上下文 深入学习资源要深入了解ToastNotifications的更多功能建议查看以下文档官方文档Docs/Configuration.md - 详细配置选项说明自定义通知指南Docs/CustomNotificatios.md - 自定义通知完整教程迁移指南Docs/Migration.md - 从v1升级到v2的指南发布说明Docs/ReleaseNotes.md - 版本更新和功能说明 总结ToastNotifications为WPF应用程序提供了强大而灵活的通知系统。通过本文的指南您应该已经掌握了✅快速安装和基础配置ToastNotifications✅创建自定义通知组件的方法和步骤✅配置通知位置和生命周期的高级选项✅实现交互式通知的实用技巧✅调试和优化通知性能的最佳实践ToastNotifications的插件化架构和高度可扩展性使其成为WPF应用程序通知系统的理想选择。无论是简单的信息提示还是复杂的交互式通知ToastNotifications都能提供优雅的解决方案。现在就开始使用ToastNotifications为您的WPF应用程序添加专业级的通知体验吧【免费下载链接】ToastNotificationsToast notifications for WPF allows you to create and display rich notifications in WPF applications. Its highly configurable with set of built-in options like positions, behaviours, themes and many others. Its extendable, it gives you possibility to create custom and interactive notifications in simply manner.项目地址: https://gitcode.com/gh_mirrors/to/ToastNotifications创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考