Home > database >  Detect click outside of control
Detect click outside of control

Time:10-20

I would like to handle click outside control (slider) in WPF application.

In my application slider is enabled and remains enabled until user clicks on another control or main window (in general outside slider). When clickoutside slider is raised slider should be disabled.

I've tried following things:

  • Handle click from main window and disable slider inside MainWindow click event. This solution was not working because MainWindow click event is raised also when I am clicking on slider itself.

  • PreviewMouseDownOutsideCapturedElementEvent based on: this question. This solution also didnt work because CaputreMouse on slider caused slider thumb movement blocking and mouse didn't follow click on track (IsMoveToPointEnabled).

  • LostFocus event on slider - event is not raised.

         private void Slider_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
         {
            Slider.Focus();        
         }
    
        //event not raised
         private void Slider_LostFocus(object sender, RoutedEventArgs e)
         {
           Slider.IsEnabled = false;
         }
    
        //changing focus in another control
         private void Slider2_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
         {
           Slider2.Focus();        
         }
    

Is there another solution that I could try?

CodePudding user response:

The code below disables a slider with name 'MySlider' as soon as anyone clicks in the window but not on the slider.

    private void Window_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        if (!(e.Source is Slider s && s.Name == "MySlider"))
            MySlider.IsEnabled = false;
    }

It doesn't ever re-enable it, but you didn't ask for that?

  • Related