单选按钮未在屏幕加载时预先选择

radio button not pre-selecting on screen loading

我觉得这很奇怪。我无法让单选按钮预先 select 一个保存的值,这让我抓狂。我有这个 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>

此外,即使我将 SelectedValue 替换为硬编码文字值“1”(对于收入),单选按钮仍然显示为空白。唯一可行的方法是在 3 个选项中的每一个上设置 IsChecked 以让它们预先 selected。

我错过了什么?

根据您的代码,我创建了一个简单的演示,但无法重现此问题。它只是正常工作。

您可以参考以下代码:

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>

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));
    }
}

注:

MyViewModel的构造函数中,我初始化变量Parity 的值如下:

  Parity = "1"; 

并且如果我们按如下方式初始化一个值,UI 将不会 pre-select 保存的值:

 Parity = 1;