BJladu4
BJladu4

Reputation: 273

How to update UI when ObservableCollection updated?

I have simple app, where ObservableCollection is updating in code and when new item added the UI is updated too. To update UI i am using a Dispatcher which is passed as a property to ViewModel. My code is works, but i don't know right i am or not.

Here is the code:

MainWindow.xaml.cs

/// <summary>
/// Логика взаимодействия для MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    MainWindowViewModel model = new MainWindowViewModel();

    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = model;
        this.model.dispatcher = this.Dispatcher;    
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        string url = urlToCheck.Text;

        Task task = new Task(() =>
        {
            model.GetUrls(url);
        });

        task.ContinueWith((previousTask) =>
        {
            label.Content = "Все ссылки собраны.";
        },
        TaskScheduler.FromCurrentSynchronizationContext());

        label.Content = "Идёт сбор ссылок...";
        task.Start();
    }
}

MainWindowViewModel.cs

 class MainWindowViewModel
{
    public ObservableCollection<Url> Urls { get; set; }
    public bool NeedToGetResponseForChildUrls { get; set; }
    public bool NeedToDeletePreviousResults { get; set; }
    public Dispatcher dispatcher;

    some code.....................


        **and something like this i am updating ObservableCollection:**

        if (NeedToDeletePreviousResults)
            {
                dispatcher.Invoke(() =>
                {
                    Urls.Clear();
                });

            }

Url.cs

    using System.Collections.ObjectModel;
using System.ComponentModel;

namespace CheckUrl
{
    public class Url : INotifyPropertyChanged
    {
        private string _absoluteUrl;
        public string AbsoluteUrl
        {
            get { return _absoluteUrl; }
            set
            {
                if (_absoluteUrl != value)
                {
                    _absoluteUrl = value;
                    OnPropertyChanged("AbsoluteUrl");
                }
            }
        }

        private int _responseStatusCode;
        public int ResponseStatusCode
        {
            get { return _responseStatusCode; }
            set
            {
                if (_responseStatusCode != value)
                {
                    _responseStatusCode = value;
                    OnPropertyChanged("ResponseStatusCode");
                }
            }
        }

        private string _responseStatusDescription;
        public string ResponseStatusDescription
        {
            get { return _responseStatusDescription; }
            set
            {
                if (_responseStatusDescription != value)
                {
                    _responseStatusDescription = value;
                    OnPropertyChanged("ResponseStatusDescription");
                }
            }
        }

        public enum Status { Working, Broken };

        private Status _urlStatus;
        public Status UrlStatus
        {
            get { return _urlStatus; }
            set
            {
                if (_urlStatus != value)
                {
                    _urlStatus = value;
                    OnPropertyChanged("UrlStatus");
                }
            }
        }

        private string _color;
        public string Color
        {
            get { return _color; }
            set
            {
                if (_color != value)
                {
                    _color = value;
                    OnPropertyChanged("Color");
                }
            }
        }

        private ObservableCollection<ChildUrl> _childUrlsValue = new ObservableCollection<ChildUrl>();
        public ObservableCollection<ChildUrl> ChildUrls
        {
            get
            {
                return _childUrlsValue;
            }
            set
            {
                _childUrlsValue = value;
            }
        }

        /// <summary>
        /// Конструктор класса Url.
        /// </summary>
        public Url(string absoluteUrl, int responseStatusCode, string responseStatusDescription, Status urlStatus, string color)
        {
            this.AbsoluteUrl = absoluteUrl;
            this.ResponseStatusCode = responseStatusCode;
            this.ResponseStatusDescription = responseStatusDescription;
            this.UrlStatus = urlStatus;
            this.Color = color;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            { 
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

Upvotes: 2

Views: 2715

Answers (1)

Tal Malaki
Tal Malaki

Reputation: 422

ObservableCollection can update your UI automaticaly by using binding. Use a list of ObservableCollection and add / remove items from is. Make the ObservableCollection as a public property.In the MainWindow constructor write:

This.DataContext=This;

Use binding to your listBox / any other control you need to show the items on. ObservableCollection allready implement IINotifyPropertyChanged in it. Once you change the items in your ObservableCollection your UI will change as well.

Upvotes: 2

Related Questions