C# 尝试使用计时器事件从datepicker和textbox获取数据

C# 尝试使用计时器事件从datepicker和textbox获取数据,c#,wpf,events,timer,C#,Wpf,Events,Timer,我试图从名为targetDate的“日期选择器”和名为targetour和targetMinute的两个“文本框”获取数据。我想每秒钟读一读里面的内容。因此,我创建了一个计时器,如下所示: System.Timers.Timer tmr = null; private void SetTimer() { tmr = new System.Timers.Timer(1000); tmr.AutoReset = true; tmr.Elapsed += TimerEvent;

我试图从名为
targetDate
的“日期选择器”和名为
targetour
targetMinute
的两个“文本框”获取数据。我想每秒钟读一读里面的内容。因此,我创建了一个计时器,如下所示:

System.Timers.Timer tmr = null;
private void SetTimer()
{
    tmr = new System.Timers.Timer(1000);
    tmr.AutoReset = true;
    tmr.Elapsed += TimerEvent;
    tmr.Enabled = true;
}
计时器运行良好,我也在获取数据。目前,仅出于验证目的,我将从
targetDate
targetour
targetMinute
中获得的任何内容显示到
TimerEvent
中的另一个文本框
differenceTime

Dispatcher.BeginInvoke(new ThreadStart(() => targetDT = targetDate.Text));
Dispatcher.BeginInvoke(new ThreadStart(() => targethh = Int32.Parse(targetHour.Text)));
Dispatcher.BeginInvoke(new ThreadStart(() => targetmm = Int32.Parse(targetMinute.Text)));
//temp = targetDT + " " + targethh + ":" + targetMinute;
Dispatcher.BeginInvoke(new ThreadStart(() => differenceTime.Text = targetDT + "-" + targethh));

以上代码工作正常。我的主要问题是,有没有更好的方法来做到这一点,而不必使用
Dispatcher.BeginInvoke
?同样,但不太重要的是,如果我尝试使用
temp
字符串填充
differenceTime
它不起作用,为什么会这样呢?

您使用的WPF正确吗

然后尝试使用
System.Windows.Timer.dispatchermer
而不是
System.Timers.Timer
dispatchermer
将在UI线程上运行,因此可能对ms不太准确,但不需要所有的
BeginInvoke
调用

我的主要问题是,有没有更好的方法来做到这一点,而不必使用
Dispatcher.BeginInvoke

按照@Jeff R的建议,将
System.Timers.Timer
替换为
dispatchermer
,并处理其
Tick
事件。然后,
Tick
事件处理程序中的代码将始终在UI线程上执行,这意味着您可以直接访问控件

您还可以通过只调用一次
Dispatcher.BeginInvoke
来改进当前代码:

Dispatcher.BeginInvoke(new Action(() =>
{
    targetDT = targetDate.Text;
    targethh = Int32.Parse(targetHour.Text);
    targetmm = Int32.Parse(targetMinute.Text);
    differenceTime.Text = targetDT + "-" + targethh;
}));
同样,但不太重要的是,如果我尝试使用临时字符串来填充不同的时间,它不起作用,为什么

因为
Dispatcher.BeginInvoke
在您传递给它的委托在UI线程上执行之前返回。您可能希望使用
调度程序。请改为调用


@γηρ∑κω′αεπ∑λλ∑Δδασ∑κμε这是wpfy你可以将所有这些代码包装在一个
BeginInvoke
中,然后
temp
也将开始工作。不工作意味着temp字符串是空的,其中没有任何内容。