Force update notifications for DependencyProperty even when it doesn't change

非 Y 不嫁゛ 提交于 2019-12-11 04:47:11

问题


I have a custom WPF control. It has a typical DependencyProperty, let's call it Status, which is updated periodically via binding. (More specifically, it is bound to a property which sends notifications according to INotifyPropertyChanged).

I want to implement a certain 'expiration' behaviour: if Status is not updated for a certain time, something happens. Ideally, this logics should be within my custom control (I have many instances of it). I set up a DispatcherTimer in the Status change handler and do what I need. All fine.

The problem is, usually, Status is updated to the same value, i.e. doesn't actually change. Yet even in this case it should reset the expiration timer.

Even if I force my view model (that implements INotifyPropertyChanged) to send the notifications on assignment regardless of whether the value changed, the WPF DependencyProperty implementation is smart enough to check for the change on its own, and it doesn't call my PropertyChangeCallback that I registered for Status (in FrameworkPropertyMetadata).

What is the best thing to do?

I could create another DependencyProperty in my control that I would always change upon assignment to Status (say, assign a random number or flip a bool), and do my timer handling there. But this seems to be an ugly and very roundabout way, especially to use.


回答1:


Just to answer my own question and provide at least some solution, in the end I did what @Janne suggested. I made a wrapper class over int, so each assignment created a new object and was treated as such. (I did not override the Equals method to do numerical comparison of the Status, so the DP could only use object identity check).

As a downside, this must create a lot of small garbage (there are 100+ real-time assignments per second over the whole life of the app), but this wasn't problematic; esp. given that WPF boxes everything anyway.



来源:https://stackoverflow.com/questions/38654075/force-update-notifications-for-dependencyproperty-even-when-it-doesnt-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!