Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: Slider doesnt raise MouseLeftButtonDown or MouseLeftButtonUp

I tried this XAML:

<Slider Width="250" Height="25" Minimum="0" Maximum="1" MouseLeftButtonDown="slider_MouseLeftButtonDown" MouseLeftButtonUp="slider_MouseLeftButtonUp" />

And this C#:

private void slider_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
sliderMouseDown = true;
}

private void slider_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
sliderMouseDown = false;
}

The sliderMouseDown variable never changes because the MouseLeftButtonDown and MouseLeftButtonUp events are never raised. How can I get this code to work when a user has the left mouse button down on a slider to have a bool value set to true, and when the mouse is up, the bool is set to false?

like image 561
Nick Avatar asked Oct 02 '08 05:10

Nick


1 Answers

Another way to do it (and possibly better depending on your scenario) is to register an event handler in procedural code like the following:

this.AddHandler
(
    Slider.MouseLeftButtonDownEvent,
    new MouseButtonEventHandler(slider_MouseLeftButtonDown),
    true
);

Please note the true argument. It basically says that you want to receive that event even if it has been marked as handled. Unfortunately, hooking up an event handler like this can only be done from procedural code and not from xaml.

In other words, with this method, you can register an event handler for the normal event (which bubbles) instead of the preview event which tunnels (and therefore occur at different times).

See the Digging Deeper sidebar on page 70 of WPF Unleashed for more info.

like image 153
cplotts Avatar answered Sep 20 '22 21:09

cplotts