问题
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.
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.
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.
回答1:
The simplest way would be for you to set a bit flag somewhere and only handle the event if the flag has the appropriate value:
bool isSystemFired = false;
And then in your event handler:
if(isSystemFired)
{
isSystemFired = false;
return;
}
And, obviously, before your automated code does anything to trigger the event handler you can set the flat to true.
回答2:
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.
On the slider set the NotifyOnSourceUpdated property to true.
<Slider x:Name="slider" Value="{Binding SliderValue, NotifyOnSourceUpdated=True,UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"></Slider>
The parent container of the slider can handle the SourceUpdate event
<Grid Binding.SourceUpdated="Slider_TargetUpdated">
private void Slider_TargetUpdated(object sender, DataTransferEventArgs e)
{
}
来源:https://stackoverflow.com/questions/25593774/differ-between-valuechanged-by-user-or-automatically-on-slider