在我的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,如下所示; 但它不会更新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));
}
}
答案 0 :(得分:1)
您在视图中绑定的属性必须实现INotifyPropertyChanged
。在您的情况下,您已绑定到snippet.DownloadPercentage
,因此代码段类必须实现INotifyPropertyChanged
,并且必须在PropertyChanged
属性的setter中引发DownloadPercentage
事件。
您还必须确保只修改UI线程中的DownloadPercentage
属性,否则如果从另一个线程修改,您将获得异常。这通常通过使用调度程序来完成:
Dispatcher.BeginInvoke(() =>
{
item.snippet.DownloadPercentage = progressPercentage;
});