仅当用户更改值时才会发生的 WPF Slider 事件
WPF Slider event which occurs only when the value is changed by the user
我正在制作一个音乐播放器,我需要在其中创建一个搜索。现在我已经在 WinForms 中以这种方式使用 TrackBar 完成了它:
- 使用定时器来保持媒体的位置和 TrackBar 的值同步。
- 当用户拖动 TrackBar 的拇指时,使用
Scroll
事件更改媒体位置。
但在 WPF 中,没有 Scroll
事件,即使在代码中更改了值,ValueChanged
事件也会触发。因此,当我使用 DispatcherTimer
更新滑块位置时,即使这样 ValueChanged
事件也会被触发,这反过来会改变媒体位置。因此,媒体无法正常播放。
所以我需要一个仅在用户更改 Slider
的值时触发的事件。
我已经遇到了 this question 但是没有正确的答案。
如有任何帮助,我们将不胜感激。感谢期待。
在您的 ValueChanged
事件处理程序中,检查一些属性以查看用户交互。
IsFocused, IsMouseDirectlyOver, IsMouseOver, IsKeyboardFocused, IsKeyboardFocusWithin
您可以这样做:首先,定义一个 class 变量:
private double newValue = 0;
然后,每当您想在代码中更改滑块的值时,首先存储新值:
newValue = <<whatever you need>>;
slider1.Value = newValue;
然后在您的事件处理程序中包含以下检查:
private void slider1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (e.NewValue != newValue)
{
newValue = e.NewValue;
// DO SOMETHING
}
}
我正在制作一个音乐播放器,我需要在其中创建一个搜索。现在我已经在 WinForms 中以这种方式使用 TrackBar 完成了它:
- 使用定时器来保持媒体的位置和 TrackBar 的值同步。
- 当用户拖动 TrackBar 的拇指时,使用
Scroll
事件更改媒体位置。
但在 WPF 中,没有 Scroll
事件,即使在代码中更改了值,ValueChanged
事件也会触发。因此,当我使用 DispatcherTimer
更新滑块位置时,即使这样 ValueChanged
事件也会被触发,这反过来会改变媒体位置。因此,媒体无法正常播放。
所以我需要一个仅在用户更改 Slider
的值时触发的事件。
我已经遇到了 this question 但是没有正确的答案。
如有任何帮助,我们将不胜感激。感谢期待。
在您的 ValueChanged
事件处理程序中,检查一些属性以查看用户交互。
IsFocused, IsMouseDirectlyOver, IsMouseOver, IsKeyboardFocused, IsKeyboardFocusWithin
您可以这样做:首先,定义一个 class 变量:
private double newValue = 0;
然后,每当您想在代码中更改滑块的值时,首先存储新值:
newValue = <<whatever you need>>;
slider1.Value = newValue;
然后在您的事件处理程序中包含以下检查:
private void slider1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (e.NewValue != newValue)
{
newValue = e.NewValue;
// DO SOMETHING
}
}