我需要在滑块的拇指被拖动到新值时触发事件,或者使用对齐点击到新值。我只希望在使用鼠标这两种方式更改值时发生此事件,因此ValueChanged事件将无效。
答案 0 :(得分:0)
你可以尝试这个小技巧
首先,您需要将UpdateSourceTrigger设置为Explicit
<Slider Minimum="0"
Thumb.DragStarted="Slider_DragStarted"
Thumb.DragCompleted="Slider_DragCompleted"
Maximum="{Binding YourMaxBinding, Mode=OneWay}"
Value="{Binding CurrentPosition, Mode=TwoWay, UpdateSourceTrigger=Explicit}" />
背后的代码
private void Slider_DragStarted(object sender, System.Windows.Controls.Primitives.DragStartedEventArgs e) {
// try to prevent updating slider position from your view model
yourViewModel.DontUpdateSliderPosition = true;
}
private void Slider_DragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e) {
BindingExpression be = ((Slider)sender).GetBindingExpression(RangeBase.ValueProperty);
if (be != null) {
be.UpdateSource();
}
yourViewModel.DontUpdateSliderPosition = false;
}
您的视图模型中的代码
private bool _dontUpdateSliderPosition;
public bool DontUpdateSliderPosition {
get {
return _dontUpdateSliderPosition;
}
set {
if (Equals(value, _dontUpdateSliderPosition)) {
return;
}
_dontUpdateSliderPosition = value;
yourPropertyChangedFunc("DontUpdateSliderPosition");
}
}
private int _currentPosition;
public int CurrentPosition {
get {
return _currentPosition;
}
set {
if (Equals(value, _currentPosition)) {
return;
}
_currentPosition = value;
yourPropertyChangedFunc("CurrentPosition");
}
}
private CodeBehindFuncToChangeTheSliderPosition(){
if (!DontUpdateSliderPosition) {
CurrentPosition = theNewPosition;
}
}
希望这会有所帮助