Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF - Stop radio button click with message box

Tags:

c#

wpf

xaml

I have a set of dynamically generated radio buttons that when clicked, fill a large amount of textboxes with data. They are bound to a property on the view model that pulls data from a service based on the radio button's label text.

What I want to do is to show a MessageBox when the radio button is clicked, so if the user accidentally (or intentionally) clicks another radio button, I can confirm that's what they wanted to do.

I can catch the click event and display a MessageBox, but the underlying property is changed anyway, triggering the data change. Is there a way that I can stop execution while the MessageBox is shown? Is the Click event the wrong event to use? I'm pretty new to WPF.

Radio button click event:

private void RadioButton_Click(object sender, RoutedEventArgs e)
{
  var radioButton = sender as RadioButton;
  MessageBoxResult result = MessageBox.Show("Choosing this sample will override any changes you've made. Continue?", "Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Question);
  if (result == MessageBoxResult.Yes)
  {
    radioButton.IsChecked = true;
    return;
  }
}

After the second line of the method and before the user's choice is returned is when the property is updated anyway.

like image 327
JB06 Avatar asked Dec 08 '25 08:12

JB06


1 Answers

Click event is raised after RadioButton is already checked but you can use PreviewMouseLeftButtonDown event instead and set Handled to true

<RadioButton ... PreviewMouseLeftButtonDown="RadioButton_PreviewMouseLeftButtonDown"/>

and in code

private void RadioButton_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    e.Handled = true;
    var radioButton = sender as RadioButton;
    MessageBoxResult result = MessageBox.Show("Choosing this sample will override any changes you've made. Continue?", "Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Question);
    if (result == MessageBoxResult.Yes)
    {
        radioButton.IsChecked = true;
    }
}
like image 97
dkozl Avatar answered Dec 09 '25 23:12

dkozl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!