我有一個 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 時,所有單選按鈕都丟失了。任何幫助將不勝感激。
uj5u.com熱心網友回復:
當你使用 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);
}
}
這是螢屏截圖:

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/317330.html
