从另一个线程更新ObservableCollection
本文关键字:ObservableCollection 更新 线程 另一个 | 更新日期: 2023-09-27 18:04:24
我有一个问题。找了很多,却找不到解决的办法。我需要,从另一个线程,更新一个ObservableCollection没有UI冻结。我使用NET4.0。这段代码不允许我看到"ProgressRing"answers"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
,你这么做了吗?