如何从静态方法更新标签?
我有一个Textblock控件
<TextBlock x:Name="lblFreeSize" TextWrapping="Wrap" Text="Free size:"/>
我想从静态方法更新它
lblFreeSize.Text = "Free size: " + Helper.SizeSuffix(App.free_space.arguments.sizebytes);
这里是助手类: - )
public static class Helper
{
public static string SizeSuffix(Int64 value)
{
return "something";
}
}
当然,返回的错误是Invalid cross-thread access.
这是Stack Trace
at MS.Internal.XcpImports.CheckThread()
at System.Windows.DependencyObject.SetValueInternal(DependencyProperty dp, Object value, Boolean allowReadOnlySet)
at System.Windows.Controls.TextBlock.set_Text(String value)
at Tr.MainPage.GetResponsetStreamCallback(IAsyncResult callbackResult)
答案 0 :(得分:2)
尝试以下
Dispatcher.BeginInvoke(new Action(() =>
lblFreeSize.Text = string.Format(
"Free size: {0}", Helper.SizeSuffix(App.free_space.arguments.sizebytes)))));
这将在关联的UI线程中异步执行操作委托。
答案 1 :(得分:0)
使用全局变量。
App.xaml.cs
public new static App Current
{
get
{
return (App)Application.Current;
}
}
static public myTextBlock = null;
在TextBlock所在的页面:
OnNavigateTo(...)
{
App.myTextBlock = lblFreeSize;
}
OnNavigatedFrom(...)
{
App.myTextBlock = null;
}
而不是lblFreeSize.Text
使用:
if ( App.myTextBlock != null )
{
App.myTextBlock = "text";
}