【发布时间】:2014-10-30 22:09:20
【问题描述】:
下午好,
我正在尝试在视图模型中触发 ICommand...从视图模型,而不是从 UI。
该命令在 UI xaml 中可以正常工作,但是在这种不同的场景中,它不能。
private DispatcherTimer telTimer;
public RelayCommand StartT_Command { get { return new RelayCommand(Exe_StartT_Command); } }
void Exe_StartT_Command(object parameter)
{
if (telTimer != null && telTimer.IsEnabled)
{
telTimer.Stop();
return;
}
telTimer = new DispatcherTimer();
telTimer.Tick += new EventHandler(TelTimerTick);
telTimer.Interval = new TimeSpan(0, 0, 0, 0, 10);
telTimer.Start();
}
private void TelTimerTick(object sender, EventArgs e) //Every Tick
{
Data.Te(Td);
}
就像我说的,它在 UI 上运行良好,但是,当被调用时(见下文),它一直运行到 telTimer.Start();然后......没有。
void KeyDown(int vKey)
{
if (vKey == 0x6A) //Num Pad * Key
{
this.StartT_Command.Execute(null);
}
}
有什么想法吗??
提前致谢。
EDIT1:我检查了.IsEnabled,并启用了计时器。但是,TelTimerTick() 没有运行。
EDIT2:我没有提到 KeyDown 是从不同的线程调用的。这会对触发 TelTimerTick() 的事件产生影响吗?
【问题讨论】:
-
是的,它必须在调度程序线程上触发,你应该得到一些异常......讨厌的黑客 App.Current.Dispatcher.BeginInvoke(new Action(ExeStartTCommand));或者只是将调度程序提供给您的虚拟机,您应该在 ViewModelBase 类中真正拥有它。
标签: c# wpf mvvm viewmodel relaycommand