更新 Listview itemsource 以 Xamarin 形式清除其中的单选按钮控件

Updating Listview itemsource clears radiobutton control inside it in Xamarin forms

我有一个简单的 Xamarin 表单列表视图。定义如下。

<ListView x:Name="lvRadio" Grid.Row="1"
           SeparatorVisibility="None"             
           VerticalOptions="CenterAndExpand"
                                      HorizontalOptions="StartAndExpand" HasUnevenRows="True" BackgroundColor="#ffffff"
                                       HeightRequest="300">
                                <ListView.ItemTemplate>
                                    <DataTemplate>
                                        <ViewCell>
                                            <StackLayout BackgroundColor="White">
                                                <RadioButton   BackgroundColor="#ffffff"
                                                                                 Content="{Binding Description}" 
                                                                                 FontFamily="Roboto" FontSize="16" TextColor="Black"
                                                                                 ></RadioButton>
                                            </StackLayout>
                                        </ViewCell>
                                    </DataTemplate>
                                </ListView.ItemTemplate>
                            </ListView>

在后面的代码中,我按如下方式绑定列表视图

            List<CommonModel> temp = new List<CommonModel>();
            CommonModel model;

            model = new CommonModel();
            model.Description = "Radio 1";
            temp.Add(model);

            model = new CommonModel();
            model.Description = "Radio 2";
            temp.Add(model);

            model = new CommonModel();
            model.Description = "Radio 3";
            temp.Add(model);

            lvRadio.ItemsSource = null;
            lvRadio.ItemsSource = temp;

现在,当我更新 ItemsSource 时,所有单选按钮都丢失了。 任何帮助将不胜感激。

当您使用 lvRadio.ItemsSource = null;lvRadio.ItemsSource = temp;

会导致listview的所有值都被修改,所以会有问题

有两种解决方法:

  1. 修改ListView为ObservableCollection,

    删除 lvRadio.ItemsSource= 空;lvRadio.ItemsSource = 临时;

    这样每次修改temp的值,界面都会 自动地 已填,原值不变。

  2. RadioButton 有一个 IsChecked 属性 来记录是否 RadioButton 被选中,因此您可以将 属性 添加到 CommonModel记录是否选择了IsChecked。然后使用 IsChecked="{绑定 xxx}"

这是第一个解决方案的cs页面代码:

public partial class MainPage : ContentPage
{
    ObservableCollection<CommonModel> temp = new ObservableCollection<CommonModel>();
    CommonModel model;
    public MainPage()
    {
        InitializeComponent();
        lvRadio.ItemsSource = temp;
    }
    private void Button_Clicked(object sender, EventArgs e)
    {
        model = new CommonModel();
        model.Description = "Radio 1";
        temp.Add(model);
        model = new CommonModel();
        model.Description = "Radio 2";
        temp.Add(model);
        model = new CommonModel();
        model.Description = "Radio 3";
        temp.Add(model);
    }
}

截图如下: