【发布时间】:2015-11-02 02:50:42
【问题描述】:
我正在创建一个自定义用户控件,它使用计时器来计算时间并最终在视图模型中运行命令操作。
问题
当时间过去时,它运行经过的事件,然后执行一个静态命令。
事实是当我点击刷新按钮时,它可以进入RefreshCommand_Executed(这是意料之中的)。但是,即使在 BeginInvoke 中的代码运行后,它也无法为触发的计时器超时事件进入此函数(这是意外)...
请帮忙。
代码
-CustomControl.xaml.cs
public partial class CustomControl : UserControl
{
public static ICommand ExecuteCommand = new RoutedCommand();
public CustomControl()
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.AutoReset = true;
timer.Interval = 60000.0;
timer.Elapsed += (sender, e) =>
{
this.Dispatcher.BeginInvoke(new Action(() =>
{
if (ExecuteCommand != null)
{
ExecuteCommand.Execute(sender);
}
}));
};
timer.Start();
}
private void ExecuteCommand_Executed(object sender, RoutedEventArgs e)
{
if (ExecuteCommand != null)
{
ExecuteCommand.Execute(sender);
}
}
}
-CustomControl.xaml
<UserControl ...skip...>
<Grid>
<Button x:Name="refreshButton"
Content="Refresh"
Click="ExecuteCommand_Executed" />
</Grid>
</UserControl>
-MainView.xaml
<UserControl ...skip...>
<UserControl.Resources>
<vm:MainViewModel x:Key="ViewModel" />
</UserControl.Resources>
<Grid cmd:RelayCommandBinding.ViewModel="{StaticResource ViewModel}">
<cmd:RelayCommandBinding Command="ctr:CustomControl.ExecuteCommand" CommandName="RefreshCommand" />
</Grid>
</UserControl>
-MainViewModel.cs
public class MainViewModel : NotifyPropertyChanged
{
private ICommand refreshCommand;
public ICommand RefreshCommand
{
get { return refreshCommand; }
set { if (value != refreshCommand) { refreshCommand = value; RaisePropertyChanged("RefreshCommand"); } }
}
public MainViewModel()
{
RefreshCommand = new RelayCommand(RefreshCommand_Executed);
}
void RefreshCommand_Executed(object o)
{
//code to run
}
}
【问题讨论】:
-
让
MainViewModel负责创建计时器并响应计时器触发不是有意义吗? -
我知道可以,但我的目标是创建一个用户控件...
标签: c# .net mvvm relaycommand system.timers.timer