执行命令不能与RelayCommand一起工作
本文关键字:一起 工作 RelayCommand 命令 不能 执行 | 更新日期: 2023-09-27 18:07:17
我正在创建一个自定义用户控件,它使用计时器来计算时间,并最终在视图模型中运行命令动作。
当时间过去时,它运行经过的事件,然后执行一个静态命令。
事实是,当我单击刷新按钮时,它可以输入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
}
}
您的计时器可能被垃圾收集。试着在你的控件中保存它的引用,并检查它是否有效。
顺便说一下,您可以使用Dispatcher Timer而避免自己使用Dispatcher。