首页 > 解决方案 > 根据来自另一个方法的字符串命名 DispatcherTimer?

问题描述

我正在尝试生成 16 个唯一的 DispatcherTimers,而不必为每个重新创建代码。但是,我无法弄清楚如何根据转换为按下按钮字符串的内容动态命名它们。

最初,我是单独设置每个计时器,但这最终导致维护的代码太多。现在,我有一个方法可以在单击 16 个按钮中的一个时触发,该方法将字符串设置为按钮的内容并将其传递给第二个方法来设置调度程序计时器。

我不能只在按钮单击方法中命名计时器并传递它,因为它告诉我它已经在封闭范围中用于定义本地或参数。我尝试通过将字符串“timer”连接到变量名称的末尾来命名计时器,但它不喜欢这样。

单击按钮后

        public void StartBtnClicked(object sender, RoutedEventArgs e)
        {
            string btn = (sender as Button).Content.ToString();
            string timerName = btn + "timer";
            DispatcherTimerSetup(btn);
        }

设置定时器

        public void DispatcherTimerSetup(string passedBtn)
        {
            DispatcherTimer passedBtn + "Timer" = new DispatcherTimer();
        }

我现在的目标是将计时器命名为“Button1ContentTimer”。我将使用计时器在完成后触发事件,并且它们将具有不同的 TimeSpan。我还将实现一个启动/停止所有按钮,这就是我命名它们的原因,所以我可以在启动/停止所有方法中一次调用它们。

编辑:

我现在正在创建计时器并将它们添加到字典中。计时器的名称都相同,但它们包含的字符串会有所不同。

        public void DispatcherTimerSetup(string btn)
        {
            Dictionary<string, DispatcherTimer> timerDict =
                new Dictionary<string, DispatcherTimer>(); //Set up a dictionary to house all the timers in

            DispatcherTimer timer = new DispatcherTimer();

            try
            {
                timerDict.Add(btn, timer);
            }
            catch (ArgumentException)
            {
                MessageBox.Show("This timer is already running");
            }
        }

StopAll 方法将接收字典并针对内部的每个计时器对其进行迭代。


        static public void StopAll(Dictionary<string, DispatcherTimer> timerDict)
        {
            foreach(KeyValuePair<string,DispatcherTimer> entry in timerDict)
            {

            }
        }

我剩下的唯一问题是如何真正停止这些计时器?以前,我只会调用 timerName.Stop(); 多次,每个计时器使用不同的计时器名称。

但是现在计时器在字典中都被命名为相同的 &,我不知道如何访问它们。我试过了:

        static public void StopAll(Dictionary<string, DispatcherTimer> timerDict)
        {

            foreach(KeyValuePair<string,DispatcherTimer> entry in timerDict)
            {
                timerDict.Remove(DispatcherTimer);
            }
        }

,但它告诉我 DispatcherTimer 是一种在给定上下文中无效的类型。我什至不确定从字典中删除它是正确的做法,这会阻止它吗?还是我需要以不同的方式解决这个问题?我觉得应该有一种方法可以按顺序从字典中实际调用每个 DispatcherTimer 元素,但我还没有弄清楚那个。

标签: c#wpfdispatchertimer

解决方案


以下是文档的链接:

字典

调度器定时器

要停止计时器,您可以执行以下操作。请注意,仅从字典中删除计时器并不会停止它。

static public void StopAll(Dictionary<string, DispatcherTimer> timerDict)
{
    foreach(var timer in timerDict.Values) timer.Stop();
    timerDict.Clear();
}

static public void StopTimer(string TimerName, Dictionary<string, DispatcherTimer> timerDict)
{
    if (timerDict.ContainsKey(TimerName)
    {
        timerDict[TimerName].Stop();
        timerDict.Remove(TimerName);
    }        
}

推荐阅读