'radio button not pre-selecting on screen loading

I feel this is weird. i can't get the Radio button to pre-select a saved value and it's driving me mad. I have this xaml:

    <StackLayout Orientation="Horizontal" RadioButtonGroup.GroupName="Parities"
                 RadioButtonGroup.SelectedValue="{Binding Parity}">
        <RadioButton Value="1" Content="Income" />
        <RadioButton Value="-1" Content="Expense" />
        <RadioButton Value="0" Content="Neutral" />
    </StackLayout>

Furthermore, even if I replace SelectedValue with a hard coded literal value "1" (for Income), the radio button still show up blank. The only way that works is by setting IsChecked on each of the 3 options to have the them pre-selected.

What am I missing?



Solution 1:[1]

Based on your code ,I created a simple demo, but I couldn't reproduce this problem. It just works properly.

You can refer to the following code:

MyPage.xaml

<ContentPage.BindingContext>
    <radiobuttondemos:MyViewModel></radiobuttondemos:MyViewModel>
</ContentPage.BindingContext>

<StackLayout>

    <StackLayout Orientation="Horizontal" RadioButtonGroup.GroupName="{Binding GroupName}"
             RadioButtonGroup.SelectedValue="{Binding Parity}">
        <RadioButton Value="1" Content="Income" />
        <RadioButton Value="-1" Content="Expense" />
        <RadioButton Value="0" Content="Neutral" />
    </StackLayout>

</StackLayout>

The MyViewModel.cs

public class MyViewModel : INotifyPropertyChanged
{
    string groupName;

    object parity;
    public object Parity
    {
        get => parity;
        set
        {
            parity = value;
            OnPropertyChanged(nameof(Parity));
        }
    }


    public MyViewModel () {

        GroupName = "Parities";

        Parity = "1";
    }

    public string GroupName
    {
        get => groupName;
        set
        {
            groupName = value;
            OnPropertyChanged(nameof(GroupName));
        }
    }


    public event PropertyChangedEventHandler PropertyChanged;

    void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

Note:

In the constructor of MyViewModel, I initialize the value of variable Parity as follows:

  Parity = "1"; 

And if we initialize a value as follows, the UI will not pre-select the saved value :

 Parity = 1;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1