Systenics Solutions Logo
  • Home start here
  • Solutions services we provide
  • Products products we build
  • About Us who we are
  • Contact Us request a quote
  • Jobs work for us
  • Blog our views

Blog

Home / Blog

Uncheck Radio Button in WPF

  • by:
  • in:
  • tags: .NET, C-Sharp
  • 0 Comments

Introduction

Recently I found myself in need of uncheck my selected Radio Button in WPF (Windows Presentation Framework). Unfortunately Radio Button has an unchecked event but it doesn’t fire. I thought of implementing uncheck onClick event, but even in this case it always givesChecked valuetrue after clicking on Radio Button. I started searching for examples in internet, but didn’t find an appropriate way to achieve this. One way I thought of styling the Checkbox to look like a Radio Button, but doing so is also had few issues. Then I thought of extending the Radio Button and use Dependency Property to achieve the same. This article describes the implementation of the Radio Button that supports uncheck and the way you can use it in your own applications. You can find the full implementation ofRadioButtonExtensionclass in the attached demo.

Using the Code

Create a new WPF application in Visual Studio 2012. Then add a new class in your project and give a name asRadioButtonExtension. Inherit the class withRadioButton object so that we can extend its events. Now in the constructor ofRadioButtonExtension class initialize the events of radio buttons as shown Listing 1 below:

Listing 1 - RadioButtonExtension.cs – modified constructor and events

public class RadioButtonExtension : RadioButton
{
  public RadioButtonExtension()
  {
    this.Checked += RadioButtonExtension_Checked; 
    this.Click += RadioButtonExtension_Click;
  }

  void RadioButtonExtension_Click(object sender, System.Windows.RoutedEventArgs e)
  {
  }

  void RadioButtonExtension_Checked(object sender, System.Windows.RoutedEventArgs e)
  {
           
  }
}

 

Now create a Dependency Property in RadioButtonExtension.cs in order to change the checked property of Radio Button as follows:

Listing 2 – Dependency Property

public bool? IsCheckedChanged
{   
  get { return (bool?)GetValue(IsCheckedChangedProperty); }
  set { SetValue(IsCheckedChangedProperty, value); }
}

// Using a DependencyProperty as the backing store for IsChanged.  
  // This enables animation, styling, binding, etc...
public static readonly DependencyProperty IsCheckedChangedProperty =
           DependencyProperty.Register("IsChanged", typeof(bool?), 
           typeof(RadioButtonExtension),
            new FrameworkPropertyMetadata(false, 
           FrameworkPropertyMetadataOptions.Journal |
         FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
        CheckedChanged));
  
 public static void CheckedChanged(DependencyObject d,
        DependencyPropertyChangedEventArgs e)
{
            ((RadioButtonExtension)d).IsChecked = (bool)e.NewValue;
}

 

Lastly create a static int property, WasChecked which will help us to know the previous status of Checkbox. I update the value of the WasChecked property in the Click and Checked event. I also update the dependency property IsCheckedChanged which will call CheckedChanged method on property change and assign the Checked value of Radio Button with the new value as shown in listing 3 below.

Listing 3 -  Modifying WasChecked property and IsCheckedChanged dependency property

public static int WasChecked { get; set; }
 
void RadioButtonExtension_Click(object sender, System.Windows.RoutedEventArgs e)
{
  if (WasChecked > 0)
  {
    this.IsCheckedChanged = !this.IsCheckedChanged;
  }
  WasChecked = 1;
} 
  
void RadioButtonExtension_Checked(object sender, System.Windows.RoutedEventArgs e)
{
  this.IsCheckedChanged = true;
   WasChecked = 0;
}

The way this works is that when RadioButton is checked, the Checked event is fired which sets WasChecked = 0 and IsCheckedChanged  =true. Then Click event is fired where I set WasChecked = 1.
Similarly, when the RadioButton is clicked again it fires the Click event in which case it checks WasChecked > 0, so it sets the dependency property IsCheckedChanged   = false. Which fires the event CheckedChanged which assigns the new value to the RadioButton.

The full source code of the RadioButtonExtension class is shown in listing 4 below:

Listing 4 – Full RadioButtonExtension class source code

using System.Windows;
using System.Windows.Controls;
  
namespace RadioButtonSam
{
  public class RadioButtonExtension : RadioButton
  {
    public static int WasChecked { get; set; }

    public bool? IsCheckedChanged
    {   
       get { return (bool?)GetValue(IsCheckedChangedProperty); }
       set { SetValue(IsCheckedChangedProperty, value); }
    }
   
    // Using a DependencyProperty as the backing store for IsChanged.  
   //This enables animation, styling, binding, etc...
  public static readonly DependencyProperty IsCheckedChangedProperty =
        DependencyProperty.Register("IsChanged", typeof(bool?), 
          typeof(RadioButtonExtension),
      new FrameworkPropertyMetadata(false, 
      FrameworkPropertyMetadataOptions.Journal |
      FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
        CheckedChanged));
     
     public static void CheckedChanged(DependencyObject d, 
              DependencyPropertyChangedEventArgs e)
     {
       ((RadioButtonExtension)d).IsChecked = (bool)e.NewValue;
     }
   
     public RadioButtonExtension()
     {
        this.Checked += new RoutedEventHandler(RadioButtonExtension_Checked); 
        this.Click += RadioButtonExtension_Click;
     }

     void RadioButtonExtension_Click(object sender, System.Windows.RoutedEventArgs e)
     {
        if (WasChecked > 0)
        {
          this.IsCheckedChanged = !this.IsCheckedChanged;
        }
        WasChecked = 1;
     } 

    void RadioButtonExtension_Checked(object sender, System.Windows.RoutedEventArgs e)
    {
      this.IsCheckedChanged = true;
      WasChecked = 0;
    }
  }
}

To use this new RadioButtonExtension in your project, you can include it in your MainWindow.xaml as shown in listing 5 below:

Listing 5 – Using RadioButtonExtension in MainWindow.xaml

<Window x:Class="RadioButtonSam.MainWindow"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         Title="MainWindow" Height="350" Width="525"
         xmlns:controls="clr-namespace:RadioButtonSam">
    <StackPanel>
      <RadioButton x:Name="rdMyRadio" Checked="rdMyRadio_Checked_1" Unchecked="rdMyRadio_Unchecked_1"    
            Content="My Radio Button" />
        <controls:RadioButtonExtension Content="My Custom Radio Button"
            GroupName="GR1" />
        <controls:RadioButtonExtension Content="My 2nd Custom Radio Button"
            GroupName="GR1" />
        <controls:RadioButtonExtension Content="My 3rd Custom Radio Button" 
            GroupName="GR2" />
    </StackPanel>
</Window>

Hope that this would help you in your projects which help me a lot.

Click here to download the source file.

Share This Post:

About the Author

This post was written by on Saturday March 23, 2013.

Related Posts
  • Integration of Nexmo SMS and Verify API using C# for AuctionWorx - 15 March 2017
  • Use Lets Encrypt SSL with AuctionWorx - 25 April 2017
  • Enable TLS 1.2 for Authorize.Net and Salesforce API calls - 13 July 2017
  • Use Lucene.Net in for faster data search - 12 February 2017
  • Integrate Salesforce with C# or ASP.NET MVC Application - 15 December 2015
comments powered by Disqus
Newer >
All Categories
  • Programming
  • General
  • DevOps
Tags
  • .NET (9)
  • Ajax (1)
  • Android (3)
  • ASP.NET (1)
  • ASP.NET 4.5 (1)
  • ASP.NET 5 (1)
  • ASP.NET 6 (1)
  • asp.net core (1)
  • ASP.NET MVC (12)
  • AuctionWorx (2)
  • Bootstrap (4)
  • Build and Release (1)
  • CI (1)
  • ClickOnce (1)
  • ClientDependency (1)
  • Code Signing (1)
  • Continuous Integration (1)
  • C-Sharp (9)
  • devops (1)
  • ExpressJS (1)
  • Interview Process (1)
  • iOS (1)
  • Linux (1)
  • Lucene (1)
  • MVC (2)
  • NodeJS (1)
  • Phonegap (3)
  • Razor (4)
  • Salesforce (2)
  • Socket.IO (1)
  • SQL CE 3.5 SP2 (1)
  • SQL Server (1)
  • Sync (1)
  • Sync Framework v2.1 (1)
  • Umbraco 6 (6)
  • Umbraco 7 (4)
  • Visual Studio 2015 (1)
  • Visual Studio Online (1)
  • VMWare ESXI 6.0 (1)
  • WCF (1)
  • Windows (2)
  • WPF (2)

About Us

Systenics Solutions is a customized software development company. We specialize in building Cloud, Web, and Mobile based applications using the latest Cloud Technologies. Our fine-tuned agile processes help you smoothly progress from conceptualizing your ideas, building proto-types/wireframes to bringing your product to market, giving our clients complete visibility and control at all times. We strive to provide our global clients of various sizes with cost effective benefits of offshore development while providing expert technical services.


Microsoft Partner - Gold Cloud Platform

Contact Us

Systenics Solutions

The Affaires, Unit #F-1, 1st Floor, Plot #9, Sector - 17, Opp. Bhumiraj Costarica, Sanpada, Navi Mumbai - 400705, India

 

Telephone: +91-22-2781 0808

Email: info@systenics.com

Skype: saurabhn

Testimonials

"Coming from a non-technical background, Saurabh and his team at Systenics took my business idea and turned it into a fully functional application which surpassed my expectations! You can be sure with them that all your IT related concerns will be covered."

Shobhan, CEO - IITJobs Inc

"The ability Systenics showed in code signing and deploying my click once code in Microsoft visual was truly awesome. I interviewed and tested 6 different development companies and only one was actually able to get the job done - that was Systenics Solutions! Professional, courteous and reliable - I highly recommend them and am very happy and eager to continue growing our business relationship now and in the near future. Thank you Saurabh"

Andre Pierre

I contracted with Systenics about 6 months ago, in an effort to customize auction software for a new company I am launching in the US. The entire process was as smooth as could be. Their estimate for the project was reasonable, and very close to the final number. I would absolutely use this company again, and I have so much confidence in their ability to work with me, I even agreed to a support agreement with them long term. Their ability to communicate with me in the US was always very timely. They listened to my thoughts and ideas, and then suggested some changes, that made my software have even greater value. I cannot thank them enough, and would highly suggest their quality services to anyone. A completely satisfied customer!

Joe Lefebvre - Pharmabid, LLC

Systenics did a great job on our customization , they clearly understood the requirements and completed the task in a timely manner. They were very thorough in project discussions and made sure that we understood how the customization works and suggested improvements when required

Mike Singh - Dr. Liquidator

Copyright © 2012-2018 Systenics Solutions. All rights reserved.

BACK TO TOP