![](/img/trans.png)
[英]How to properly update the ObservableCollection from another thread?
[英]Update ObservableCollection from another thread
我有个问题。 寻找了很多,但找不到解决方案。 我需要从另一个线程更新UI冻结的ObservableCollection。 我正在使用NET4.0。 此代码不允许我看到“ ProgressRing”和“ Searching”消息。 谢谢!
private void Search()
{
ShowMessage = "Searching..."; // Message while the search is made.
IsBusy = true; // Show WPF Toolkit BusyIndicator
ShowProgressRing = true; // To show a ProgressRing in BusyIndicator
Task.Factory.StartNew(() =>
{
Articles = new ObservableCollection<Article>();
/////////////////////////////
//// Simulate SQL query ////
///////////////////////////
for (var i = 0; i < 1000; i++)
{
Articles.Add(new Article
{
Code = i.ToString(),
Name = "PRODUCT NAME",
Price = 1m
});
}
}).ContinueWith(x =>
{
IsBusy = false; // Hide
}, TaskScheduler.FromCurrentSynchronizationContext());
}
编辑
private bool _showProgressRing;
public bool ShowProgressRing
{
get { return _showProgressRing; }
set
{
_showProgressRing = value;
RaisePropertyChanged("ShowProgressRing");
}
}
private bool _isBusy;
public bool IsBusy
{
get { return _isBusy; }
set
{
_isBusy = value;
RaisePropertyChanged("IsBusy");
}
}
private string _showMessage;
public string ShowMessage
{
get { return _showMessage; }
set
{
_showMessage = value;
RaisePropertyChanged("ShowMessage");
}
}
我的VM从ViewModelBase继承(MVVM Light)
我假设您的ShowMessage是这样定义的:
private string _ShowMessage ;
public string ShowMessage
{
get
{
return _ShowMessage;
}
set
{
this.Set<string>("ShowMessage ", ref this._ShowMessage , value);
}
}
与您的IsBusy属性相同:
private string _IsBusy ;
public bool IsBusy
{
get
{
return _IsBusy ;
}
set
{
this.Set<bool>("IsBusy ", ref this._IsBusy , value);
}
}
和相同的
private string _ShowProgressRing;
public bool ShowProgressRing
{
get
{
return _ShowProgressRing;
}
set
{
this.Set<bool>("ShowProgressRing", ref this._ShowProgressRing, value);
}
}
并且整个类都继承自ObservableObject
,您这样做了吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.