问题描述
我在 xamarin 中有一个列表视图,当我尝试在按钮单击事件中投射 selecteditem 时,它给了我错误。 SavedVira 类用于 sqlite 数据库表,我正在尝试使用 async 但它似乎更麻烦然后值得。 (我对编程很陌生)。这是我的代码:
XAML:
<ListView x:Name="SavedViraview" HasUnevenRows="True" ItemTapped="SavedViraview_ItemTapped">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<StackLayout Padding="10">
<Label Text="Navn:" FontSize="18" FontAttributes="Bold"/>
<Label Text="{Binding Virusnavn}" FontSize="15"/>
<Label Text="Symptomer:" FontSize="18" FontAttributes="Bold"/>
<Label Text="{Binding symptom1}"/>
<Label Text="{Binding symptom2}"/>
<Label Text="{Binding symptom3}"/>
<Label Text="{Binding symptom4}"/>
<Label Text="{Binding symptom5}"/>
<Label Text="{Binding symptom6}"/>
<Label Text="Lavet af:" FontSize="18" FontAttributes="Bold"/>
<Label Text="{Binding Creator}"/>
<Button Text="Load" x:Name="LoadButton" Clicked="LoadButton_Clicked"/>
</StackLayout>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
XAML.CS:
private ObservableCollection<SavedVira> SavedVira = new ObservableCollection<SavedVira>();
public Åben()
{
InitializeComponent();
}
protected override void OnAppearing()
{
nameLabel.Text = Values.currentUser;
Init();
}
private async void Init()
{
BindingContext = new SavedVira();
var Viralist = await DataServices.GetSavedVira();
SavedVira = new ObservableCollection<SavedVira>(Viralist);
SavedViraview.ItemsSource = SavedVira;
}
private void LoadButton_Clicked(object sender,EventArgs e)
{
var LoadVirus = ((ListView)sender).SelectedItem as SavedVira;
if (LoadVirus == null)
return;
Values.LoadBool = true;
Values.symptomZero = LoadVirus.symptom1;
Values.symptomOne = LoadVirus.symptom2;
Values.symptomTwo = LoadVirus.symptom3;
Values.symptomThree = LoadVirus.symptom4;
Values.symptomFour = LoadVirus.symptom5;
Values.symptomFive = LoadVirus.symptom6;
}
SavedVira 演员/模型:
[Table("savedvira")]
public class SavedVira
{
[PrimaryKey,AutoIncrement]
[Column("id")]
public int Id { get; set; }
[Column("virusnavn")]
public string Virusnavn { get; set; }
[Column("creator")]
public string Creator { get; set; }
[Column("symptoms1")]
public string symptom1 { get; set; }
[Column("symptoms2")]
public string symptom2 { get; set; }
[Column("symptoms3")]
public string symptom3 { get; set; }
[Column("symptoms4")]
public string symptom4 { get; set; }
[Column("symptoms5")]
public string symptom5 { get; set; }
[Column("symptoms6")]
public string symptom6 { get; set; }
}
任何帮助都会非常感谢!
解决方法
sender
是 Button
所以这不起作用
var LoadVirus = ((ListView)sender).SelectedItem as SavedVira;
改为这样做
var btn = (Button)sender;
var selected = (SavedVira)btn.BindingContext;
此外,对实例变量和类使用相同的名称会造成混淆,我建议您避免使用它
SavedVira = new ObservableCollection<SavedVira>(Viralist);