0

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?

  • Do you just need the [`LostFocus`](https://learn.microsoft.com/en-us/dotnet/api/system.windows.uielement.lostfocus?view=windowsdesktop-5.0) event on the slider? – DavidG Oct 19 '21 at 14:51
  • Tried, event is not raised. I will edit my question with example of this also. – qblacksheep Oct 19 '21 at 15:03

1 Answers1

0

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?

Rich N
  • 8,939
  • 3
  • 26
  • 33
  • Thank you! I've tested it for one slider and it worked great. Now I will need to extend this method for more sliders but it should be easy now. – qblacksheep Oct 19 '21 at 18:53