首页 > 解决方案 > INotifyPropertyChanged 时调用函数 - UWP c#

问题描述

我每分钟都在调用一个函数,它将值分配给 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 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; }

}

标签: c#uwpobservablecollectioninotifypropertychanged

解决方案


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

SchoolName属性为例,如果你给它设置了一个新的值,PropertyChanged事件就不会被触发,这意味着 UI 不会被更新来反映这个变化。

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

您应该PropertyChanged在属性的设置器中触发事件。并对您在绑定中使用的所有属性执行此操作。

问:如果此 observable 集合中的任何数据发生更改,我想调用另一个函数(例如:CallIfValueChanged();)。

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

当添加、删除、更改、移动项目或刷新整个列表时。

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


推荐阅读