I am creating a custom user control which use a timer to count the time and run the command action in the view model finally.
Problem
When the time passed, it run the elapsed event, then execute a static command.
The fact is that when I click the refresh button, it can enter the RefreshCommand_Executed (it is expected). However, it cannot enter this function for the timer elasped event fired even then code in BeginInvoke is run (it is unexpected)...
Please help for this.
Code
-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
}
}