我每分钟都在调用一个函数,该函数将值分配给 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();)。
您可以将事件处理程序注册到 _SelectedSchoolList
的 CollectionChanged事件,被触发
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/