fs_tigre
fs_tigre

Reputation: 10738

What is the proper way to bind a radio button in MVVM / MVVM Light

I'm currently binding my radio buttons individually, in other words, I have a command for each one, everything works fine but I would like to somehow have only one command where all of them bind.

Here is what I have...

XAML:

<RadioButton x:Name="radioButton1" 
                         Content="RadioButton1"  
                         IsChecked="True"
                         Command="{Binding RadioButton1Command }"/>
<RadioButton x:Name="radioButton2" 
                         Content="RadioButton2"  
                         IsChecked="True"
                         Command="{Binding RadioButton2Command }"/>

ViewModel:

    public RelayCommand RadioButton1Command { get; }
    public RelayCommand RadioButton2Command { get; }

    public MyClassConstructorViewModel()
    {
        RadioButton1Command = new RelayCommand(radioButton1Click);
        RadioButton1Command = new RelayCommand(radioButton2Click);
    }


    private void radioButton1Click()
    {
        Console.WriteLine("Radio Button 1 Clicked...");
    }
    private void radioButton2Click()
    {
        Console.WriteLine("Radio Button 2 Clicked...");
    }

Is there a way to bind all radio buttons to a single RelayCommand and be able to respond accordingly?

Thanks!

Upvotes: 0

Views: 4159

Answers (1)

Antoine V
Antoine V

Reputation: 7204

You can bind the name of the RadioButton. By the name received in the method, you can your right action.

XAML

<RadioButton x:Name="radioButton1" 
                         Content="RadioButton1"  
                         IsChecked="True"
                         Command="{Binding RadioButtonCommand }" CommandParameter="{Binding Path=Name, RelativeSource={RelativeSource Self}}"/>

<RadioButton x:Name="radioButton2" 
                         Content="RadioButton2"  
                         IsChecked="True"
                         Command="{Binding RadioButtonCommand }" CommandParameter="{Binding Path=Name, RelativeSource={RelativeSource Self}}"/>

ViewModel

public RelayCommand<string> RadioButtonCommand { get; }

public MyClassConstructorViewModel()
{
    RadioButtonCommand = new RelayCommand<string>(radioButtonClick);
}


private void radioButtonClick(string name)
{
    if(name == "radioButton1")
        Console.WriteLine("Radio Button 1 Clicked...");
    else if(name == "radioButton2")
        Console.WriteLine("Radio Button 2 Clicked...");
}

Upvotes: 2

Related Questions