You would normally use PointerPressed
event (see docs). However, this has two issues. First, the Thumb
already handles such pointer interaction, so PointerPressed
never bubbles out of the Slider
. Secondly, it would be triggered for any location of the Slider
, not only the thumb.
To work around this, you will need to handle the event on the Thumb
itself. First, we will create a helper method that searches the visual tree:
public T FindChild<T>(DependencyObject parent)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if (child is T typedChild)
{
return typedChild;
}
var inner = FindChild<T>(child);
if (inner != null)
{
return inner;
}
}
return default;
}
Note that this and many similar useful methods are available in the Windows Community Toolkit as part of Visual Tree Extensions.
Now, we search for the Thumb
within the control:
var thumb = FindChild<Thumb>(MySlider);
Finally, we attach the PointerPressed
event. Because it is already handled by the Slider
control itself, we need to use AddHandler
, that allows us to observe event that are marked as handled too:
thumb.AddHandler(
UIElement.PointerPressedEvent,
new PointerEventHandler(Thumb_PointerPressed),
true);
And in the handler you can then do anything you require:
private void Thumb_PointerPressed(object sender, PointerRoutedEventArgs e)
{
// ...
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…