强制更新DependencyProperty的通知,即使它没有变化 [英] Force update notifications for DependencyProperty even when it doesn't change
问题描述
我有一个自定义WPF控件。它具有典型的 DependencyProperty
,我们称之为 Status
,该状态会通过绑定定期更新。 (更具体地说,它绑定到根据 INotifyPropertyChanged
发送通知的属性)。
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
).
我要实现某种到期行为:如果 Status
在一定时间内未更新,则发生某些情况。理想情况下,此逻辑应在我的自定义控件内(我有很多实例)。我在状态
更改处理程序中设置了 DispatcherTimer
并执行我需要的操作。很好。
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.
问题通常是 Status
更新为相同的值,即实际上并没有更改。即使在这种情况下,它也应该重置过期计时器。
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.
即使我强制执行视图模型(实现 INotifyPropertyChanged
)无论值是否更改,都可以在分配时发送通知,WPF DependencyProperty
实现很聪明,可以自行检查更改,并且不会调用我为状态
(在 FrameworkPropertyMetadata
中)注册的 PropertyChangeCallback
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
).
什么是最好的事情?
我可以创建另一个 DependencyProperty
控制下,我总是会在分配给 Status
后更改(例如,分配一个随机数或翻转 bool
),然后在那里进行计时器处理。但这似乎是一种丑陋且非常round回的方式,尤其是在使用时。
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.
推荐答案
只需回答我自己的问题并提供至少有一些解决方案,最后我做了@Janne建议的事情。我在 int
上创建了一个包装器类,因此每个分配都创建了一个新对象,并因此被视为新对象。 (我没有重写 Equals
方法来对 Status
进行数值比较,所以DP只能使用对象标识
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).
缺点是,这必须创建很多小的垃圾(在应用的整个生命周期中,每秒有100多个实时分配),但这不是问题。尤其是鉴于WPF无论如何都会把所有东西都装箱。
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.
这篇关于强制更新DependencyProperty的通知,即使它没有变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!