![](/img/trans.png)
[英]Issue in making TextBlock invisible using Visibilty.Collapsed (WP7)
[英]Issue with updating a textblock in WP7 with a timer
我正在开发一款将提供倒数计时器的应用程序(作为其功能的一小部分)。 但是,在某些情况下,也可能同时存在多个倒数计时。 每个倒数计时器在枢纽视图中都有自己的枢纽项目。 由于这些倒计时是动态创建的,因此我将每个倒计时的文本块(作为剩余时间的输出)添加到列表中,并且设置了一个计时器来调用遍历每个文本块的方法在列表中并相应地更新它们。 但是,我收到“ System.UnauthorizedAccessException”的异常,但我不确定为什么。 有人告诉我这是“无效的跨线程访问”错误。
这是违规行:
c.Label.Dispatcher.BeginInvoke(delegate() { c.Label.Text = timeRemaining; });
这是完整的方法:
private static void TimeRemainingCallback(object state)
{
if (countDowns.Count == 0)
{
return;
}
foreach (CountDown c in countDowns)
{
DateTime rightNow = DateTime.Today;
if (c.ExpirationDate >= rightNow)
{
DateTime offsetExpiration = c.ExpirationDate.Add(c.LocalNow);
TimeSpan timeDifference = offsetExpiration.Subtract(rightNow);
String timeRemaining = "";
String timeDays = "";
String timeHours = "";
String timeMinutes = "";
String timeSeconds = "";
if (timeDifference.Days == 1)
{
timeDays = "1 Day";
}
else
{
timeDays = timeDifference.Days + " Days";
}
if (timeDifference.Hours == 1)
{
timeHours = "1 Hour";
}
else
{
timeHours = timeDifference.Hours + " Hours";
}
if (timeDifference.Minutes == 1)
{
timeMinutes = "1 Minute";
}
else
{
timeMinutes = timeDifference.Minutes + " Minutes";
}
if (timeDifference.Seconds == 1)
{
timeSeconds = "1 Second";
}
else
{
timeSeconds = timeDifference.Seconds + " Seconds";
}
if (timeDifference.Days == 0 && timeDifference.Hours >= 1)
{
timeRemaining = timeHours + " " + timeMinutes;
}
else if (timeDifference.Days == 0 && timeDifference.Hours == 0 && timeDifference.Minutes >= 1)
{
timeRemaining = timeMinutes + " " + timeSeconds;
}
else if (timeDifference.Days == 0 && timeDifference.Hours == 0 && timeDifference.Minutes == 0)
{
timeRemaining = timeSeconds;
}
else
{
timeRemaining = timeDays + " " + timeHours + " " + timeMinutes;
}
c.Label.Dispatcher.BeginInvoke(delegate() { c.Label.Text = timeRemaining; });
}
}
}
这是我创建计时器的方法,这是唯一提到CallBack的时间:
Timer updateRemainingTime = new Timer(TimeRemainingCallback, null, 0, 1000);
该列表实际上充满了包含日期时间和文本块(在此称为标签)的对象,因此是c.Label处理。
timeRemaining是在计时器回调中形成的剩余时间的字符串。
对这里发生的事情有任何想法吗? 有关如何执行此操作的更好的主意?
在整个循环迭代中调用Dispatcher
,并删除当前的Dispatcher调用。
Dispatcher.BeginInvoke(() =>
{
foreach (CountDown c in countDowns)
{
// Actions here.
c.Label.Text = timeRemaining;
}
});
我假设您有countDowns
绑定到正在使用的列表UI控件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.