目前在我的应用程序中,我有一个RelayCommand
来调用一个以Timer
开头的操作。我有一个单独的命令调用Dispose()
方法来摆脱/释放计时器。这一切都位于项目的ViewModel对应部分。
使用MVVM模式,关闭窗口时如何处理此Timer
,以及执行关闭窗口的常规/默认操作?
如果有任何帮助,我也在使用MVVM-Light工具包。
我目前的解决方案示例如下所示:
private static Timer dispatchTimer;
public MainViewModel()
{
this.StartTimerCommand = new RelayCommand(this.StartTimerAction);
this.StopTimerCommand = new RelayCommand(this.StopTimerAction);
}
public RelayCommand StartTimerCommand { get; private set; }
public RelayCommand StopTimerCommand { get; private set; }
private void StartTimerAction()
{
dispatchTimer = new Timer(new TimerCallback(this.IgnoreThis), null, 0, 15);
}
private void StopTimerAction()
{
dispatchTimer.Dispose();
}
....
Height="896"
Width="1109"
DataContext="{Binding Main, Source={StaticResource Locator}}">
<Grid x:Name="mainGrid"
Width="Auto"
Height="Auto">
<Button x:Name="startTimerButton"
Content="Start Timer"
Command="{Binding StartTimerCommand}"/>
<Button x:Name="stopTimerButton"
Content="Stop Timer"
Command="{Binding StopTimerCommand}"/>
</Grid>
</Window>
public MainWindow()
{
this.InitializeComponent();
//Would a 'Closing +=' event be called here?
}
答案 0 :(得分:2)
根据您的注册方式,关闭窗口可能会也可能不会处理您的viewmodel。一种方法是从视图绑定到Loaded / Unloaded事件并在那里完成工作:
查看:强>
的xmlns:ⅰ= “CLR-名称空间:System.Windows.Interactivity;装配= System.Windows.Interactivity”
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding PageLoadedCommand}"/>
</i:EventTrigger>
<i:EventTrigger EventName="Unloaded">
<i:InvokeCommandAction Command="{Binding PageUnLoadedCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<强>视图模型:强>
public RelayCommand PageUnLoadedCommand { get; private set; }
...
PageUnLoadedCommand = new RelayCommand(() => OnPageUnLoadedCommand());
...
private void OnPageUnLoadedCommand()
{
//Unsubscribe and dispose here
}
答案 1 :(得分:-1)
您可以为ViewModel
添加析构函数,如下所示
~public MainViewModel()
{
dispatchTimer.Dispose();
}