1
votes

I would like to load a screen in a WPF application that shows a person's details. I am using MVVM and C#

I have a screen that loads a persons details. From selecting a person from a list, you press select and the information of that person is loaded. Among the data is "Gender" On the usercontrol, I am using radio buttons. One for Male, one for Female. I would like to know how do I bind the result to the radio buttons, so that Joe, the person you select, is shown to be Male.

I don't want to use the radio buttons for anything but display purposes. I just want to show the gender of that person.

Is it using the radio button's Content or IsSelected binding? I know that I should use binding (obviously, if I'm using MVVM), but I don't know where.

So the person has Name (string) and Gender(string). The gender field is either Male or Female. How do I use this in Binding to show that radio button as selected?

I have the following declared in my ViewModel:

 public bool GenChecked { get; set; }

I am guessing that from there, I would say, if Gender is Male, IsSelected Gender is true? I'm not clear. This is the first time I am dabbling with radio buttons in WPF MVVM

If this question is not clear, or you would like to see some code examples, please comment and I will make edits

EDIT 1

Just to be clear. Sorry for any misunderstandings. The usercontrol/view has two radio buttons at present:

<RadioButton Content="Male" IsChecked="{Binding GenChecked}" />
<RadioButton Content="Female" IsChecked="{Binding GenChecked}" />

The viewmodel is getting the information via a class, which has Name and Gender as strings. One of the objects of the class is Joe, Male.

So on my viewmodel, I have the bool for GenChecked. If Joe.Gender = "Male" then the male radio button must be selected. But I think that if I say GenChecked is true, both would be selected?

Thats where I'm confused. Must the radio buttons be grouped? Must the binding be te same? Must it bind to the content?

Hope this clears it up some more

1
Code same please? you have two different radio buttons for male and female? [Update] you said that a person has Gender(string), so that's in your Model? and your VM has a bool ?Rachit Magon
RadioButton has a property IsChecked, you can bind any boolean to the property. But whats your exact question?Rachit Magon

1 Answers

1
votes

Assuming that true is male and false is female (and no, I don't want to start a political discussion) you can do something like this

In your xaml

<RadioButton Content="Male" IsChecked="{Binding Gender"}/>
<RadioButton Content="Female" IsChecked="{Binding Gender, Converter={StaticResource BoolToOppositeBoolConverter}}"/>

And write an IValueConverter (BoolToOppositeBoolConverter) where you have code like this

    public object Convert1(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var boolValue = bool.Parse(value.ToString());

        return !boolValue;
    }