c# - 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; }
}
解决方案
首先,您在实现中需要修复一些错误。您没有INotifyPropertyChanged
正确实现接口。
以SchoolName
属性为例,如果你给它设置了一个新的值,PropertyChanged
事件就不会被触发,这意味着 UI 不会被更新来反映这个变化。
class SelectedSchoolList : INotifyPropertyChanged
{
public string SchoolName { get; set; }
//... other code omitted
}
您应该PropertyChanged
在属性的设置器中触发事件。并对您在绑定中使用的所有属性执行此操作。
问:如果此 observable 集合中的任何数据发生更改,我想调用另一个函数(例如:CallIfValueChanged();)。
您可以将事件处理程序注册到被触发_SelectedSchoolList
的CollectionChanged事件
当添加、删除、更改、移动项目或刷新整个列表时。
在事件处理程序中调用您的方法。
推荐阅读
- php - 如何使用 PHP 添加 active 包括 OR
- flutter - 如何在windows10的c分区中构建flutter apk
- java - Java:编译器如何使用声明类型作为其超类的表达式找不到特定方法?
- python - 如何从 Python 多处理进程中打印?
- php - opencart错误致命错误:未捕获异常:错误:未知列
- javascript - Json 对象到对象
- kotlin - 由于 jsNpm 配置,KMP 库 gradle allTests 失败
- r - summarise() 使用 dplyr 的案例子集
- angular8 - 页面刷新时丢失绑定数组
- postgresql - xpath(未知,字符不同)不存在