[英]Windows Phone update binding from background thread
在我的Windows Phone 8應用程序中,我在下面有列表框
<ListBox x:Name="ListBox1" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding snippet.DownloadPercentage}"
TextWrapping="Wrap"
FontFamily="Portable User Interface"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
我正在下載文件asyn,並希望將進度百分比提供給UI,如下所示; 但不會更新用戶界面。 它始終顯示0,它是初始int值。 如果我在主線程上訪問DownloadPercentage屬性,它將毫無問題地更新。
private void ClientOnDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs downloadProgressChangedEventArgs)
{
// not working
item.snippet.DownloadPercentage = progressPercentage;
// not working
Dispatcher.BeginInvoke(delegate {
item.snippet.DownloadPercentage = progressPercentage;
});
// not working
ProgressChangedEventHandler workerProgressChanged = delegate {
item.snippet.DownloadPercentage = progressPercentage;
};
BackgroundWorker worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.ProgressChanged += workerProgressChanged;
worker.ReportProgress(progressPercentage);
// WORKING!
#region ProgressIndicator
_progressIndicator.Text = string.Format("Downloading ({0}%) {1}", progressPercentage, item.snippet.Title);
_progressIndicator.IsVisible = true;
_progressIndicator.IsIndeterminate = true;
SystemTray.SetProgressIndicator(this, _progressIndicator);
#endregion
}
我能做什么?
解; 在@DecadeMoon的提示之后,我不得不在Snippet類上實現INotifyPropertyChanged。
public class Snippet : INotifyPropertyChanged
{
[JsonProperty("downloadPercentage")]
public int DownloadPercentage
{
get { return _downloadPercentage; }
set
{
_downloadPercentage = value;
RaisePropertyChanged("DownloadPercentage");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
您在視圖中綁定到其屬性的對象必須實現INotifyPropertyChanged
。 在您的情況下,您將綁定到snippet.DownloadPercentage
,因此該代碼片段類必須實現INotifyPropertyChanged
並且必須在DownloadPercentage
屬性的設置器中引發PropertyChanged
事件。
您還必須確保僅從UI線程修改DownloadPercentage
屬性,否則,如果從另一個線程進行修改,則會出現異常。 這通常通過使用調度程序來完成:
Dispatcher.BeginInvoke(() =>
{
item.snippet.DownloadPercentage = progressPercentage;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.