【问题标题】:How to update UI when ObservableCollection updated?ObservableCollection 更新时如何更新 UI?
【发布时间】:2013-12-23 07:57:31
【问题描述】:

我有一个简单的应用程序,其中 ObservableCollection 正在更新代码,当添加新项目时,UI 也会更新。为了更新 UI,我使用了一个 Dispatcher,它作为属性传递给 ViewModel。我的代码是有效的,但我不知道我是否正确。

代码如下:

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));
            }
        }
    }
}

【问题讨论】:

  • 你能显示你的 Url Class 代码吗?
  • 您应该更喜欢在模型中使用 FromCurrentSynchronizationContext 以避免耦合到 UI 框架
  • 像这样在窗口类中添加逻辑代码也是一种糟糕的形式。在模型中创建一个 ICommand 属性,为其分配一个 RelayCommand 并将其绑定到按钮的 Command 属性而不是 Click 处理程序。
  • 看看wpf binding

标签: c# wpf binding observablecollection


【解决方案1】:

ObservableCollection 可以使用绑定自动更新您的 UI。使用 ObservableCollection 列表并从中添加/删除项目。将 ObservableCollection 设为公共属性。在 MainWindow 构造函数中写入:

This.DataContext=This;

使用绑定到您的列表框/您需要在其上显示项目的任何其他控件。 ObservableCollection 已经在其中实现了 IINotifyPropertyChanged。更改 ObservableCollection 中的项目后,您的 UI 也会随之更改。

【讨论】:

    猜你喜欢
    • 2014-01-01
    • 2016-11-05
    • 1970-01-01
    • 1970-01-01
    • 2019-03-16
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    • 2014-12-15
    相关资源
    最近更新 更多