C#从静态方法更新标签

C#从静态方法更新标签,c#,windows-phone-8,C#,Windows Phone 8,如何从静态方法更新标签 我有一个文本块控件 <TextBlock x:Name="lblFreeSize" TextWrapping="Wrap" Text="Free size:"/> 下面是helper类:-) 当然,返回的错误是无效的跨线程访问。 这是堆栈跟踪 at MS.Internal.XcpImports.CheckThread() at System.Windows.DependencyObject.SetValueInternal(DependencyProper

如何从静态方法更新标签

我有一个文本块控件

 <TextBlock x:Name="lblFreeSize" TextWrapping="Wrap" Text="Free size:"/>
下面是helper类:-)

当然,返回的错误是无效的跨线程访问。 这是堆栈跟踪

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) 
使用全局变量

App.xaml.cs

public new static App Current
{
    get
    {
        return (App)Application.Current;
    }
}

static public myTextBlock = null;
在文本块所在的页面上:

OnNavigateTo(...)
{
   App.myTextBlock = lblFreeSize;
}

OnNavigatedFrom(...)
{
   App.myTextBlock = null;
}
不要使用
lblFreeSize.Text
而使用:

if ( App.myTextBlock != null )
{
    App.myTextBlock = "text";
}
试试下面的方法

Dispatcher.BeginInvoke(new Action(() => 
    lblFreeSize.Text = string.Format(
        "Free size: {0}", Helper.SizeSuffix(App.free_space.arguments.sizebytes)))));

这将在关联的UI线程中异步执行操作委托。

乍一看,这对我来说是合理的。当您尝试时会发生什么?首先,回答这个问题:您希望您的
静态
方法如何知道您正在处理的窗口实例?为什么这个方法是静态的?这里需要更多的上下文。请参见中的
lblFreeSize.Text=
在哪里?它似乎不在静态方法中。静态方法没有对控件所在窗口的引用,除非您在调用中发送它。为什么静态方法要更新UI?方法必须是静态的吗?您所说的静态方法是
Helper
方法吗?在这种情况下,看起来您根本不是从方法更新控件,而是使用方法的结果来更新控件,这应该不会造成任何问题。@KenSmith请检查更新
if ( App.myTextBlock != null )
{
    App.myTextBlock = "text";
}
Dispatcher.BeginInvoke(new Action(() => 
    lblFreeSize.Text = string.Format(
        "Free size: {0}", Helper.SizeSuffix(App.free_space.arguments.sizebytes)))));