繁体   English   中英

Windows Phone从后台线程更新绑定

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM