从另一个线程更新ObservableCollection

时间:2016-08-27 17:34:06

标签: c# wpf multithreading .net-4.0

我有问题。寻找了很多,但找不到解决方案。我需要从另一个线程更新ObservableCollection而不冻结UI。我使用的是.NET4.0。 这段代码不允许我看到" ProgressRing"和"搜索"信息。谢谢!

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)

1 个答案:

答案 0 :(得分:0)

我假设您的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,你做到了吗?