根据另一个方法中的字符串命名DispatcherTimer?

时间:2019-05-08 12:22:45

标签: c# wpf dispatchertimer

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

本来,我是分别设置每个计时器的,但是这结束了太多代码,难以维护。现在,我有了一个方法,该方法可以在单击16个按钮之一时触发,从而将字符串设置为按钮的内容,并将其传递给第二种方法来设置分派器计时器。

我不能只是在按钮click方法中命名计时器并传递它,因为它告诉我它已经在封闭作用域中用于定义局部或参数。我尝试通过将字符串“ 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”。我将使用计时器在完成时触发事件,并且它们将具有不同的TimeSpans。我还将实现一个“开始/停止所有”按钮,这就是为什么要命名每个按钮的原因,因此我可以在“开始/停止所有”方法中一次调用它们。

编辑:

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

        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元素,但是我还无法弄清楚。

1 个答案:

答案 0 :(得分:2)

以下是文档的链接:

Dictionary

DispatcherTimer

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

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);
    }        
}