c# -在UWP中停止时间跨度的功能

本文关键字:时间跨度 功能 UWP | 更新日期: 2023-09-27 18:12:10

我用TimeSpan制作了一个简单的应用程序,每1分钟重复一首歌,制作完成后我可以在这一刻停止这首歌,但我不能通过按钮停止计时器,

我的代码
public class AlertViewModel : INotifyPropertyChanged
{
    public DispatcherTimer Timer { get; set; } = new DispatcherTimer();
    public List<int> TimeOuts { get; set; } = new List<int>();
    private int timeOut;
    public event PropertyChangedEventHandler PropertyChanged;
    private int selectedIndex;
    public int SelectedIndex
    {
        get {return selectedIndex;}
        set {selectedIndex = value; PropertyChanged(this, new PropertyChangedEventArgs("SelectedIndex")); timeOut = TimeOuts[SelectedIndex];}
    }
    public List<Sound> Sounds { get; set; } = new List<Sound>();
    public event EventHandler<EventArgs> TimeUP;
    List<TimeSpan> TName = new List<TimeSpan>();

    public AlertViewModel()
    {
        TimeOuts.Add(10);

        TimeOuts.Add(15);
        TimeOuts.Add(20);
        TimeOuts.Add(30);
        TimeOuts.Add(60);
        TimeOuts.Add(120);
        TimeOuts.Add(360);
        TimeOuts.Add(720);
        timeOut = TimeOuts[SelectedIndex];
        Timer.Interval = new TimeSpan(0, 1, 0);
        Timer.Tick += Timer_Tick;
        Sounds.Add(new Sound("Sound 1", "ms-appx:///Assets/Audio/sound1.mp3"));
        Sounds.Add(new Sound("Sound 2", "ms-appx:///Assets/Audio/sound2.mp3"));
    }
    private void Timer_Tick(object sender, object e)
    {
        // int TimeOuts = this.TimeOuts[SelectedIndex];
        timeOut--;
        if (timeOut == 0)
        {
            TimeUP(this, new EventArgs());
            timeOut = TimeOuts[SelectedIndex];
        }
    }
}

c# -在UWP中停止时间跨度的功能

但是我不能通过按钮停止计时器

你可以在ViewModel中使用DelegateCommand并将其绑定到停止按钮:

AlertViewModel:

public class AlertViewModel : INotifyPropertyChanged
{
    public RelayCommand CmdStop { get; set; }
    public AlertViewModel()
    {
         ...
         CmdStop = new RelayCommand(() => {
            if (Timer != null)
            {
                Timer.Stop();
            }
        });
    }
}
XAML:

...
<Page.DataContext>
    <local:AlertViewModel  />
</Page.DataContext>
...
<Button Name="btnStop" Command="{Binding CmdStop}">Click Me to Stop</Button>

注意:我在MvvmLight中使用RelayCommand。你可以使用任何你喜欢的框架