nmrlqa4 nmrlqa4 - 7 days ago 5
C# Question

Is there actually a way to bind Checked event of a radio button to a command in the ViewModel?

I tried with

<RadioButton Content="Boom" Command={Binding MyCommand} IsEnabled="{Binding IsChecked, Converter={StaticResource InverseBooleanConverter}, RelativeSource={RelativeSource Mode=Self}}"/>


but nothing happens. Why is that and how to fix it?

Answer

The following code works as expected:

<RadioButton Content="Boom" Command="{Binding MyCommand}" />

That is, as in case of a regular Button, MyCommand is fired every time you click a RadioButton. If you're using RadioButtons, this, understandably, may not be what you want.

More useful will be passing some sort of data as a CommandParameter to know which option was checked:

<RadioButton Content="AAA" Command="{Binding MyCommand}" CommandParameter="AAA" GroupName="MyGroup"/>
<RadioButton Content="BBB" Command="{Binding MyCommand}" CommandParameter="BBB"  GroupName="MyGroup"/>

Example command method:

    private ICommand _MyCommand;
    public ICommand MyCommand
    {
        get { return _MyCommand ?? (_MyCommand = new DelegateCommand(a => MyCommandMethod(a))); }
    }

    private void MyCommandMethod(object item)
    {
        Console.WriteLine("Chosen element: " + (string)item);
    }
Comments