0

I have a number of radio buttons which are used to change an option, by being bound to a command with a command parameter, like this:

<RadioButton
  Content="Option1"
  Command="{Binding ChangeOption}
  CommandParameter="Option1" />

The code to change options is the view model is quite simple:

public property SelectedOption { get; set; }

public void ChangeOption(string option)
{
    SelectedOption = option;
}

This is simplified a bit, but it pretty much describes the concept. What I am missing is, to decide whether or not a radio button is checked, based on the SelectedOption property. I want to compare this property to the Content (or CommandParameter) of the RadioButton. This should be done in a trigger, which can then alter the IsSelected property.

The problem is, that I cannot figure out, how to access either the Content or CommandParamater in the Data Trigger. I am stuck at something like this:

<Style.Triggers>
  <DataTrigger Binding={Binding SelectedOption} Value="?????">
    <Setter Property="IsChecked" Value="True" />
  </DataTrigger>
</Style.Triggers>

What do I put in the Value parameter of the Data Trigger, to compare it to the selected option?

Jakob Busk Sørensen
  • 5,599
  • 7
  • 44
  • 96
  • 2
    If this was a listbox with an itemtemplate containing a radiobutton then you could just bind IsSelected to IsChecked and selecteditem of the listbox to SelectedOption. And option to the content, which would then avoid any "magic string" mismatch problems. Magic strings are bad practice for that reason. – Andy Feb 21 '19 at 10:41
  • If your options are `enum` values, you can consider following [this approach](https://stackoverflow.com/questions/397556/how-to-bind-radiobuttons-to-an-enum). – dymanoid Feb 21 '19 at 11:15
  • @Andy i hadn't thought of that, but it might actually be the best way to solve the problem. Thanks. – Jakob Busk Sørensen Feb 21 '19 at 11:36

1 Answers1

0

This approach may cause you more headache than it's worth.

I would recommend creating a new class for these radio buttons:

public class OptionSelection
{
    public bool IsSelected {get; set;}
    public string Option {get; set;}
}

You can then create an ObservableCollection or List of these items and display them with an ItemsControl, binding to Option (with a Label or TextBlock) and IsSelected (with your RadioButton).

It's important to also implement INotifyPropertyChanged in this object so that the XAML bindings update accordingly.

Jack
  • 886
  • 7
  • 27