WPF RadioButtons and data binding

There is a well-known issue with WPF RadioButton controls with data binding: when a radio button is unchecked the data binding is not undone. For example, suppose you have the following two radio buttons in the same group linked to a the "IsSuccess" (of type bool?) attribute of an object:

When you check the rbSuccess radio button, the IsSuccess field becomes "true", but when you check on the rbFailure radio button (and thus uncheck the rbSuccess one), the IsSuccess field is still true!

The problem is discussed here. There are several solutions. This blog explains one (using a control template). Another popular one is to use a ListBox restyled as a radio button. However, this causes other problems such as being unable to scroll past the radiobuttons (they are really a listbox, so scrolling is done inside the list).

The solution I have found is to put each radio button in a different group and link their checked/unchecked values via the converter. Like this:

And here is the converter:

Notice the converter parameter. Its role is to make sure that I get opposite values for the two radio buttons (when one is true, the other is false).

value
(IsSuccess) param

result
RadioButton.IsChecked = !(value ^ param)

true true true false true false true false false false false true

(^ is the XOR operator in C#)

This article is part of the GWB Archives. Original Author: Clara Oscura

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.