c# - 在 INotifyPropertyChanged 时调用函数 - UWP c#

标签 c# uwp observablecollection inotifypropertychanged

我每分钟都在调用一个函数,该函数将值分配给 SelectedSchoolList 的可观察集合。如果此可观察集合中的任何数据发生更改,我想调用另一个函数(例如:CallIfValueChanged();)。我怎样才能做到这一点?

我的代码:

  public static ObservableCollection<SelectedSchoolList> _SelectedSchoolList = new ObservableCollection<SelectedSchoolList>();

        DispatcherTimer dispatcherTimer;
        dispatcherTimer = new DispatcherTimer();
        dispatcherTimer.Tick += dispatcherTimer_Tick;
        dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
        dispatcherTimer.Start();

        // callback runs on UI thread
       async void  dispatcherTimer_Tick(object sender, object e)
        {
        response_from_server = await CallWebService();
        if (!response_from_server.Equals("FAIL", StringComparison.CurrentCultureIgnoreCase))
        {
        parseJSONandAssignValuesToSelectedSchoolList (response_from_server);//this function assigns values to _SelectedSchoolList  
        }                                 
        }
      CallIfValueChanged();// I want to call this function here only if any data on '_SelectedSchoolList' is updated/changed

我的类(class):

  class SelectedSchoolList : INotifyPropertyChanged
{
    public string SchoolName { get; set; }
    public string Score { get; set; }
    public ObservableCollection<SelectedStudentList> SelectedStudentArray { get; set; }
    public event PropertyChangedEventHandler PropertyChanged;
}
public class SelectedStudentList
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }
    public string IndividualScore { get; set; }

}

最佳答案

首先,您需要在实现中修复一些错误。您没有正确实现 INotifyPropertyChanged 接口(interface)。

SchoolName 属性为例,如果你给它设置一个新值,PropertyChanged 事件根本不会被触发,这意味着 UI 不会被更新以反射(reflect)变化。

class SelectedSchoolList : INotifyPropertyChanged
{
    public string SchoolName { get; set; }
    //... other code omitted
}

您应该在属性的 setter 中触发 PropertyChanged 事件。并对您在绑定(bind)中使用的所有属性执行此操作。

问:如果此可观察集合中的任何数据发生变化,我想调用另一个函数(例如:CallIfValueChanged();)。

您可以将事件处理程序注册到 _SelectedSchoolListCollectionChanged事件,被触发

when an item is added, removed, changed, moved, or the entire list is refreshed.

在事件处理程序中调用您的方法。

关于c# - 在 INotifyPropertyChanged 时调用函数 - UWP c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51511248/

相关文章:

c# - 如何在 ASP.NET Core 中对 void 方法使用异步/等待?

c# - 在 UWP XAML 中动态绑定(bind) NavigationViewItem && NavigationViewItemHeader

javascript - UWP 应用程序 - HTML5/JS 中的 InkCanvas 和 InkToolbar

mvvm - RaisePropertyChanged不适用于ObservableCollection

c# - 我如何创建一个矩形数组的数组 C#

c# - ConfigurationSettings.AppSettings 已过时,警告

c# - 运行时代码编译出错 - 进程无法访问文件

uwp - 如何使用 makeappx 工具为创建的 appx 创建 .appxupload?

c# - 使用 System.Reactive 观察 ObservableCollection 中项目的 PropertyChanged

c# - 通过对象字段搜索 ObservableCollection