WPF 实现 Message 消息提醒控件

打印 上一主题 下一主题

主题 842|帖子 842|积分 2526

WPF 实现 Message 消息提醒控件
控   件:Message
作   者:WPFDevelopersOrg - 驚鏵
原文链接https://github.com/WPFDevelopersOrg/WPFDevelopers


  • 框架使用.NET4 至 .NET6;
  • Visual Studio 2022;
  • 接着上一篇

1)新增 MessageListBoxItem.cs 代码如下:

  • 新增了名为MessageType的依赖属性,类型为MessageBoxImage,默认值为MessageBoxImage.Information
  • 新增了名为IsCenter的依赖属性,默认值为false,为true则内容居中显示。
  1. using System.Windows;
  2. using System.Windows.Controls;
  3. namespace WPFDevelopers.Controls
  4. {
  5.     public class MessageListBoxItem : ListBoxItem
  6.     {
  7.         public MessageBoxImage MessageType
  8.         {
  9.             get { return (MessageBoxImage)GetValue(MessageTypeProperty); }
  10.             set { SetValue(MessageTypeProperty, value); }
  11.         }
  12.         public static readonly DependencyProperty MessageTypeProperty =
  13.             DependencyProperty.Register("MessageType", typeof(MessageBoxImage), typeof(MessageListBoxItem), new PropertyMetadata(MessageBoxImage.Information));
  14.         public bool IsCenter
  15.         {
  16.             get { return (bool)GetValue(IsCenterProperty); }
  17.             set { SetValue(IsCenterProperty, value); }
  18.         }
  19.         public static readonly DependencyProperty IsCenterProperty =
  20.             DependencyProperty.Register("IsCenter", typeof(bool), typeof(MessageListBoxItem), new PropertyMetadata(false));
  21.     }
  22. }
复制代码
2)新增 MessageListBox.cs 代码如下:

  • 自定义MessageListBox继承ListBox,其中重写了两个方法:IsItemItsOwnContainerOverride和GetContainerForItemOverride。


      • IsItemItsOwnContainerOverride方法用于确定给定的项是否应该作为其自己的容器。在这里,它检查传入的item对象是否是MessageListBoxItem的实例。如果是,则返回true,表示该项是其自己的容器;否则,返回false。


      • GetContainerForItemOverride方法用于创建并返回一个新的容器对象,用于承载列表框中的项。在这里,它创建并返回一个MessageListBoxItem的实例作为容器对象。


  1. using System.Windows;
  2. using System.Windows.Controls;
  3. namespace WPFDevelopers.Controls
  4. {
  5.     public class MessageListBox : ListBox
  6.     {
  7.         protected override bool IsItemItsOwnContainerOverride(object item)
  8.         {
  9.             return item is MessageListBoxItem;
  10.         }
  11.         protected override DependencyObject GetContainerForItemOverride()
  12.         {
  13.             return new MessageListBoxItem();
  14.         }
  15.     }
  16. }
复制代码
3)新增 MessageAdorner.cs 代码如下:

  • MessageAdorner是一个继承自Adorner的自定义类。它用于在装饰元素上显示消息的附加装饰器。
  • 构造函数MessageAdorner(UIElement adornedElement)接受一个UIElement类型的参数,作为要进行装饰的元素。
  • Push方法用于将消息添加到装饰器中。它接受消息内容、消息类型和是否居中显示的参数。如果装饰器尚未创建,则会创建一个MessageListBox并将其设置为装饰器的子元素。然后,根据传入的参数创建一个新的MessageListBoxItem,并将其插入到列表框的顶部。
  • Child属性用于获取或设置装饰器的子元素。当设置子元素时,会将子元素添加到装饰器的可视化子元素集合中;当子元素为null时,会从可视化子元素集合中移除子元素。
  • VisualChildrenCount属性返回装饰器的可视化子元素数量。
  • ArrangeOverride方法用于调整装饰器的布局。在这里,根据装饰元素的宽度和子元素的期望大小,计算出子元素的水平位置,并将其排列在装饰器的顶部。
  • GetVisualChild方法用于获取指定索引处的可视化子元素。在这里,如果索引为0且子元素不为null,则返回子元素;否则,调用基类的方法返回对应索引的可视化子元素。
  1. using System.Windows;
  2. using System.Windows.Documents;
  3. using System.Windows.Media;
  4. namespace WPFDevelopers.Controls
  5. {
  6.     public class MessageAdorner : Adorner
  7.     {
  8.         private MessageListBox listBox;
  9.         private UIElement _child;
  10.         private FrameworkElement adornedElement;
  11.         public MessageAdorner(UIElement adornedElement) : base(adornedElement)
  12.         {
  13.             this.adornedElement = adornedElement as FrameworkElement;
  14.         }
  15.         public void Push(string message, MessageBoxImage type = MessageBoxImage.Information, bool center = false)
  16.         {
  17.             if (listBox == null)
  18.             {
  19.                 listBox = new MessageListBox();
  20.                 Child = listBox;
  21.             }
  22.             var mItem = new MessageListBoxItem { Content = message, MessageType = type, IsCenter = center };
  23.             listBox.Items.Insert(0, mItem);
  24.         }
  25.         public UIElement Child
  26.         {
  27.             get => _child;
  28.             set
  29.             {
  30.                 if (value == null)
  31.                 {
  32.                     RemoveVisualChild(_child);
  33.                     _child = value;
  34.                     return;
  35.                 }
  36.                 AddVisualChild(value);
  37.                 _child = value;
  38.             }
  39.         }
  40.         protected override int VisualChildrenCount
  41.         {
  42.             get
  43.             {
  44.                 return _child != null ? 1 : 0;
  45.             }
  46.         }
  47.         protected override Size ArrangeOverride(Size finalSize)
  48.         {
  49.             var x = (adornedElement.ActualWidth - _child.DesiredSize.Width) / 2;
  50.             _child.Arrange(new Rect(new Point(x, 0), _child.DesiredSize));
  51.             return finalSize;
  52.         }
  53.         protected override Visual GetVisualChild(int index)
  54.         {
  55.             if (index == 0 && _child != null) return _child;
  56.             return base.GetVisualChild(index);
  57.         }
  58.     }
  59. }
复制代码
4)新增 Message.cs 代码如下:

  • CreateMessageAdorner方法用于创建消息装饰器MessageAdorner。它接受一些参数,如窗口所有者Window owner、消息内容string message、消息类型MessageBoxImage type和是否居中显示bool center。在方法内部,它首先检查是否已经存在消息装饰器实例messageAdorner,如果存在,则调用装饰器的Push方法将新的消息添加到装饰器中,并直接返回。如果不存在消息装饰器实例,则根据提供的窗口所有者或获取默认窗口ControlsHelper.GetDefaultWindow(),然后获取对应的装饰层AdornerLayer。如果装饰层为空,则抛出异常。接着,创建一个新的消息装饰器实例,并将其添加到装饰层中。最后,调用装饰器的Push方法将消息添加到装饰器中。
  • Push方法是一个扩展方法,用于在指定的窗口上显示消息。它接受窗口对象Window owner作为第一个参数,以及其他参数,如消息内容string message、消息类型MessageBoxImage type和是否居中显示bool center。在方法内部,它调用CreateMessageAdorner方法,并传递相应的参数。
  • 另一个重载的Push方法是直接在静态上下文中调用的。它接受消息内容string message、消息类型MessageBoxImage type和是否居中显示bool center作为参数,并调用CreateMessageAdorner方法。
  1. using System;
  2. using System.Linq;
  3. using System.Windows;
  4. using WPFDevelopers.Helpers;
  5. namespace WPFDevelopers.Controls
  6. {
  7.     public static class Message
  8.     {
  9.         private static MessageAdorner messageAdorner;
  10.         static void CreateMessageAdorner(Window owner = null, string message = null, MessageBoxImage type = MessageBoxImage.Information, bool center = false)
  11.         {
  12.             try
  13.             {
  14.                 if (messageAdorner != null)
  15.                 {
  16.                     messageAdorner.Push(message, type, center);
  17.                     return;
  18.                 }
  19.                 if (owner == null)
  20.                     owner = ControlsHelper.GetDefaultWindow();
  21.                 var layer = ControlsHelper.GetAdornerLayer(owner);
  22.                 if (layer == null)
  23.                     throw new Exception("not AdornerLayer is null");
  24.                 messageAdorner = new MessageAdorner(layer);
  25.                 layer.Add(messageAdorner);
  26.                 messageAdorner.Push(message, type, center);
  27.             }
  28.             catch (Exception)
  29.             {
  30.                 throw;
  31.             }
  32.         }
  33.         public static void Push(this Window owner, string message, MessageBoxImage type = MessageBoxImage.Information, bool center = false)
  34.         {
  35.             CreateMessageAdorner(owner, message, type, center);
  36.         }
  37.         public static void Push(string message, MessageBoxImage type = MessageBoxImage.Information, bool center = false)
  38.         {
  39.             CreateMessageAdorner(message: message, type: type, center: center);
  40.         }
  41.     }
  42. }
复制代码
5)新增 MessageListBoxItem.xaml 代码如下:

  • XAML 代码定义一个名为Storyboard_Loaded的故事板(Storyboard),其中包含了四个DoubleAnimation 动画

    • 第一个DoubleAnimation动画将目标元素PART_SmallPanel的Y轴缩放属性ScaleTransform.ScaleY 从 0 变化到 1,持续时间为0.2秒。这会使PART_SmallPanel在加载时以渐变的方式显示出来。
    • 第二个DoubleAnimation动画将目标元素PART_SmallPanel的不透明度属性Opacity从0.1变化到1,持续时间为0.2秒。这也是为了使PART_SmallPanel在加载时以渐变的方式显示出来。
    • 第三个DoubleAnimation动画将目标元素PART_SmallPanel的Y轴缩放属性ScaleTransform.ScaleY从1变化到0,持续时间为0.2秒。这个动画在10秒后开始执行,会使PART_SmallPanel以渐变的方式从可见状态变为不可见状态。
    • 第四个DoubleAnimation动画将目标元素PART_SmallPanel的不透明度属性Opacity从1变化到0,持续时间为0.2秒。同样地,在10秒后开始执行,使PART_SmallPanel以渐变的方式从可见状态变为不可见状态。

  • 定义一个名为Storyboard_Close的故事板Storyboard,其中包含了两个DoubleAnimation动画。

    • 第一个DoubleAnimation动画将目标元素PART_SmallPanel的Y轴缩放属性(UIElement.RenderTransform).(ScaleTransform.ScaleY)从1变化到0,持续时间为0.2秒。这会使PART_SmallPanel以渐变的方式从可见状态变为不可见状态。
    • 第二个DoubleAnimation动画将目标元素PART_SmallPanel的不透明度属性(Opacity)从1变化到0,持续时间为0秒。该动画在0.2秒后开始执行,使PART_SmallPanel以立即消失的方式从可见状态变为不可见状态。

  1. <ResourceDictionary
  2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.     xmlns:controls="clr-namespace:WPFDevelopers.Controls"
  5.     xmlns:helpers="clr-namespace:WPFDevelopers.Helpers">
  6.     <ResourceDictionary.MergedDictionaries>
  7.         <ResourceDictionary Source="Basic/ControlBasic.xaml" />
  8.     </ResourceDictionary.MergedDictionaries>
  9.    
  10.    
  11.     <Style BasedOn="{StaticResource WD.MessageListBoxItem}" TargetType="{x:Type controls:MessageListBoxItem}" />
  12.     <Style BasedOn="{StaticResource WD.MessageListBox}" TargetType="{x:Type controls:MessageListBox}" />
  13. </ResourceDictionary>
复制代码
6)新增 ListBoxItemExtensions 代码如下:

  • 在方法内部,首先将sender转换为ListBoxItem类型,并进行空引用检查。然后,创建一个绑定对象binding,将其源设置为当前的item,并将绑定模式设置为单向。
  • 接下来,使用DependencyPropertyDescriptor从UIElement.OpacityProperty属性获取一个依赖属性描述符dpd。通过调用AddValueChanged方法,将一个值更改事件的处理程序添加到item上。当item的不透明度Opacity小于0.1时,该处理程序将执行以下操作:

    • 获取父级ItemsControl,即包含item的列表框。
    • 如果找到了父级ItemsControl,则使用ItemContainerGenerator从item获取关联的数据项(selectedItem)。
    • 从父级ItemsControl的Items集合中移除selectedItem。
    • 调用父级ItemsControl的Refresh方法,以刷新列表框的显示。

  1. using System.ComponentModel;
  2. using System.Windows;
  3. using System.Windows.Controls;
  4. using System.Windows.Data;
  5. namespace WPFDevelopers.Helpers
  6. {
  7.     public static class ListBoxItemExtensions
  8.     {
  9.         public static readonly DependencyProperty AutoRemoveOnOpacityZeroProperty =
  10.         DependencyProperty.RegisterAttached("AutoRemoveOnOpacityZero", typeof(bool), typeof(ListBoxItemExtensions), new PropertyMetadata(false, OnAutoRemoveOnOpacityZeroChanged));
  11.         public static bool GetAutoRemoveOnOpacityZero(DependencyObject obj)
  12.         {
  13.             return (bool)obj.GetValue(AutoRemoveOnOpacityZeroProperty);
  14.         }
  15.         public static void SetAutoRemoveOnOpacityZero(DependencyObject obj, bool value)
  16.         {
  17.             obj.SetValue(AutoRemoveOnOpacityZeroProperty, value);
  18.         }
  19.         private static void OnAutoRemoveOnOpacityZeroChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
  20.         {
  21.             ListBoxItem item = obj as ListBoxItem;
  22.             if (item != null)
  23.             {
  24.                 if ((bool)e.NewValue)
  25.                     item.Loaded += Item_Loaded;
  26.                 else
  27.                     item.Loaded -= Item_Loaded;
  28.             }
  29.         }
  30.         private static void Item_Loaded(object sender, RoutedEventArgs e)
  31.         {
  32.             var item = sender as ListBoxItem;
  33.             if (item != null)
  34.             {
  35.                 var binding = new Binding("Opacity");
  36.                 binding.Source = item;
  37.                 binding.Mode = BindingMode.OneWay;
  38.                 var dpd = DependencyPropertyDescriptor.FromProperty(UIElement.OpacityProperty, typeof(UIElement));
  39.                 dpd.AddValueChanged(item, (s, args) =>
  40.                 {
  41.                     if (item.Opacity < 0.1)
  42.                     {
  43.                         var parent = ItemsControl.ItemsControlFromItemContainer(item);
  44.                         if (parent != null)
  45.                         {
  46.                             object selectedItem = parent.ItemContainerGenerator.ItemFromContainer(item);
  47.                             parent.Items.Remove(selectedItem);
  48.                             parent.Items.Refresh();
  49.                         }
  50.                     }
  51.                 });
  52.             }
  53.         }
  54.     }
  55. }
复制代码
7)新增 示例 代码如下:
  1. <ResourceDictionary
  2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.     xmlns:controls="clr-namespace:WPFDevelopers.Controls"
  5.     xmlns:helpers="clr-namespace:WPFDevelopers.Helpers">
  6.     <ResourceDictionary.MergedDictionaries>
  7.         <ResourceDictionary Source="Basic/ControlBasic.xaml" />
  8.     </ResourceDictionary.MergedDictionaries>
  9.    
  10.    
  11.     <Style BasedOn="{StaticResource WD.MessageListBoxItem}" TargetType="{x:Type controls:MessageListBoxItem}" />
  12.     <Style BasedOn="{StaticResource WD.MessageListBox}" TargetType="{x:Type controls:MessageListBox}" />
  13. </ResourceDictionary> <ResourceDictionary
  14.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  15.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  16.     xmlns:controls="clr-namespace:WPFDevelopers.Controls"
  17.     xmlns:helpers="clr-namespace:WPFDevelopers.Helpers">
  18.     <ResourceDictionary.MergedDictionaries>
  19.         <ResourceDictionary Source="Basic/ControlBasic.xaml" />
  20.     </ResourceDictionary.MergedDictionaries>
  21.    
  22.    
  23.     <Style BasedOn="{StaticResource WD.MessageListBoxItem}" TargetType="{x:Type controls:MessageListBoxItem}" />
  24.     <Style BasedOn="{StaticResource WD.MessageListBox}" TargetType="{x:Type controls:MessageListBox}" />
  25. </ResourceDictionary>                  
复制代码
8) 示例 代码如下:
  1. private void AddButton_Click(object sender, RoutedEventArgs e)
  2.         {
  3.             var btn = sender as Button;
  4.             switch (btn.Tag)
  5.             {
  6.                 case "Info":
  7.                     Message.Push(App.Current.MainWindow, "This is a info message", MessageBoxImage.Information);
  8.                     break;
  9.                 case "Error":
  10.                     Message.Push("This is a error message", MessageBoxImage.Error, true);
  11.                     break;
  12.                 case "Warning":
  13.                     Message.Push("This is a warning message", MessageBoxImage.Warning, true);
  14.                     break;
  15.                 case "Question":
  16.                     Message.Push("This is a question message", MessageBoxImage.Question);
  17.                     break;
  18.                 default:
  19.                     Message.Push("这是一条很长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长消息", MessageBoxImage.Information);
  20.                     break;
  21.             }
  22.         }
复制代码

码云

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

灌篮少年

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表