mvvmtoolkit+snackbar弹窗消息通知
需求场景:
在MainView.xaml下添加一个SnackBar并将其ZIndex设置成1,后续所有的消息弹窗都通过MainView来展示
代码设置:
MVVMToolkit+MaterialDesignThemes+全局静态类
MainView下添加SnackBar,SnackBar下的消息数据以及是否展示属性绑定至一个全局消息类中,后续所有的消息展示则可以通过全局消息静态类中的方法以及属性来进行
View下的静态属性绑定如下
IsActive="{Binding Path=MessageActive, Source={x:Static local:GlobalMessage.Instance}}"
MessageQueue="{Binding Path=MessageQueue, Source={x:Static local:GlobalMessage.Instance}}"
ViewModel下使用消息如下
GlobalMessage.Instance.ShowMessageDialog("XXXX");
完整代码为
XAML前端代码如下
<Window
x:Class="SnackbarTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:SnackbarTest"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="800"
Height="450"
mc:Ignorable="d">
<Grid>
<materialDesign:Snackbar
Margin="10"
VerticalAlignment="Top"
Panel.ZIndex="1"
IsActive="{Binding Path=MessageActive, Source={x:Static local:GlobalMessage.Instance}}"
MessageQueue="{Binding Path=MessageQueue, Source={x:Static local:GlobalMessage.Instance}}" />
<StackPanel>
<TextBox Margin="10" Text="{Binding Mess}" />
<Button
Margin="10"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Command="{Binding ShowCommand}"
Content="消息展示" />
</StackPanel>
</Grid>
</Window>
ViewModel如下
public class MainViewModel : ObservableRecipient
{
private string _mess = "";
public string Mess
{
get => _mess;
set => SetProperty(ref _mess, value);
}
public RelayCommand ShowCommand { get; }
public MainViewModel()
{
ShowCommand = new RelayCommand(Show);
}
public void Show()
{
GlobalMessage.Instance.ShowMessageDialog(Mess);
}
}
全局消息静态类如下
/// <summary>
/// 全局静态单例消息类,用于全局显示静态消息,属性绑定至MainWindow下
/// </summary>
public class GlobalMessage : ObservableRecipient
{
private GlobalMessage()
{ }
public static GlobalMessage Instance { private set; get; } = new GlobalMessage();
//是否弹窗显示消息
private bool _messageActive = false;
public bool MessageActive
{
get => _messageActive;
set => SetProperty(ref _messageActive, value);
}
//消息显示框数据
private SnackbarMessageQueue _messageQueue = new SnackbarMessageQueue();
public SnackbarMessageQueue MessageQueue
{
get => _messageQueue;
set => SetProperty(ref _messageQueue, value);
}
/// <summary>
/// 显示弹窗提示消息
/// </summary>
/// <param name="message"></param>
public void ShowMessageDialog(string message)
{
//延时1秒后消息消失
MessageActive = true;
MessageQueue.Enqueue(message, null, null, null, false, false, TimeSpan.FromSeconds(1));
}
}
显示效果为: