问题描述
我有一个包含 Slider sli
的 WPF 应用程序,它通常会在 ValueChanged
事件上触发一个方法.此外,在某些情况下,sli
的最大值和最小值会发生变化.现在我已经意识到,在那些情况下,sli
的 Value
可能会在超出新的最大/最小值范围的情况下发生变化.这也会触发 ValueChanged
.此外,我有时必须以编程方式调整 Value
,这当然也会触发 `ValueChanged.
I have a WPF application that includes a Slider sli
, which in general fires a method on the ValueChanged
-event. In addition, in certain cases the maximal and minimal values of sli
are changed. Now I have realized that in those cases the Value
of sli
might change in the case that it was out of range of the new max/min values. This will also fire ValueChanged
. In addition I sometimes have to adjust Value
programmatically, which will of course also fire `ValueChanged.
现在,我只希望在用户更改 Value
时执行该方法,而不是在它被强制更改时执行,因为它超出范围或当我在代码中更改它时.
Now, I only wish to execute the method if the user changed Value
, but not if it was forcefully changed, because it went out of range or when I change it in code.
我的尝试是使用 DragCompleted
-事件,但我确实希望在用户拖动滑块时连续触发该事件.另一种尝试是在 max/min-change 或 in-code-update 之前从 ValueChanged
的事件处理程序中简单地删除该方法,然后再添加该方法.在这里,我不确定这是否真的是最干净,尤其是性能方面最快的解决方案.
My attempt was using the DragCompleted
-event, but I do wish to fire the event continuously while the user drags the slider head. Another attempt was to simply remove the method from the event handler for ValueChanged
before a max/min-change or in-code-update and add the method afterwards. Here, I am not sure if that is really the cleanest and especially the fastest solution performance-wise.
因此,我想问是否有人可能有更好的解决方案,也许是实际上众所周知的东西,但是,我找不到关于这个话题的任何东西.
Thus, I wanted to ask if someone might have a nicer solution, maybe something that is actually commenly known, however, I couldn't find anything on this topic.
推荐答案
您可以使用 Binding.SourceUpdated
事件来检测专用用户输入,而不是使用 ValueChanged 事件.SourceUpdated 事件仅由显式用户输入触发.
Instead of using the ValueChanged event you can use the Binding.SourceUpdated
event to detect dedicated user input. The SourceUpdated event is only triggered by explicit user input.
在滑块上将 NotifyOnSourceUpdated
属性设置为 true.
On the slider set the NotifyOnSourceUpdated
property to true.
<Slider x:Name="slider" Value="{Binding SliderValue, NotifyOnSourceUpdated=True,UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"></Slider>
滑块的父容器可以处理SourceUpdate事件
The parent container of the slider can handle the SourceUpdate event
<Grid Binding.SourceUpdated="Slider_TargetUpdated">
private void Slider_TargetUpdated(object sender, DataTransferEventArgs e)
{
}
这篇关于ValueChanged 由用户更改或在 Slider 上自动更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!