需要在窗口关闭时显示一个淡出的效果,原本在窗口后台写的话是很简单的,但MVVM模式的思想是后台代码应该连毛都没有
然后百度google俩小时都没找到相关的解决方案,也不知道是太简单了没人问还是怎么回事,自己研究了一个,原理很简单,就是在View载入的时候把自己传递给ViewModel,然后在ViewModel中处理事件。
至于为什么要这么麻烦
View
<Window x:Class="Client.Views.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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:Client.Views" mc:Ignorable="d" xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" prism:ViewModelLocator.AutoWireViewModel="True" x:Name="mainWindow" Height="900" Width="1440" WindowStartupLocation="CenterScreen"> <i:Interaction.Triggers> <i:EventTrigger EventName="Loaded"> <i:InvokeCommandAction Command="{Binding LoadCommand}" CommandParameter="{Binding ElementName=mainWindow}"/> </i:EventTrigger> </i:Interaction.Triggers> <Grid/> </Window>
给窗口一个Name,然后使用InvokeCommandAction传递参数,参数就是主窗口
ViewModel
public DelegateCommand<Window> LoadCommand { get; private set; } private Window _w; private bool canClose = false; //构造函数 public MainWindowViewModel() { LoadCommand = new DelegateCommand<Window>(Load); } //窗口载入 private void Load(Window w) { _w = w; w.Closing += (sender, e) => { if(!canClose) e.Cancel = true; }; } //关闭窗口 private void CloseWindow() { canClose = true; _w.Close(); }
在ViewModel中处理Closing事件就可以了。
关闭窗口同理,直接调用_w.Close()就行了。