0

我正在创建一个自定义用户控件,它使用计时器来计算时间并最终在视图模型中运行命令操作。

问题

当时间过去时,它运行 elapsed 事件,然后执行静态命令。

事实是,当我单击刷新按钮时,它可以进入 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
    }
}
4

1 回答 1

0

您的计时器可能已被垃圾收集。尝试在您的控件中保留对它的引用并检查它是否有效。

顺便说一句,您可以使用 Dispatcher Timer 并避免自己使用 Dispatcher。

于 2015-08-11T21:40:54.077 回答