android - 更新 Listview itemsource 在 Xamarin 表单中清除其中的单选按钮控件
问题描述
我在 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的所有值都被修改,所以会出现问题。
有两种解决方案:
将 ListView 修改为ObservableCollection,
删除lvRadio.ItemsSource= null;lvRadio.ItemsSource = temp;
这样每次修改temp的值,都会自动填充界面,不会修改原来的值。
RadioButton 有一个IsChecked属性来记录 RadioButton 是否被选中,所以可以在 CommonModel 中添加一个属性来记录 IsChecked 是否被选中。然后使用 IsChecked="{Binding 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);
}
}
这是屏幕截图:
推荐阅读
- java - 控制台重定向在应用程序关闭之前不起作用(Java)
- javascript - 未捕获(承诺中)TypeError:无法将属性'innerHTML'设置为null-我可以在console.log()中看到值
- python - 不使用 max() 和 min() 从字典中获取最大值和最小值
- ajax - Leaflet - 通过按钮单击设置 geojson 多边形数据的 choropleth
- javascript - 如何返回函数变量的值
- pygears - 是否可以在 VS Code 中运行 PyGears?
- php - 第一次使用 PHP cURL,集成 API 签名表单的小问题
- sql - 如何做 2 个子请求来计算表中的男人和女人
- python - 在我的 python 脚本中更新 requests.get
- javascript - 复制功能无法识别 p5js 中另一个画布上的图像