Saving with SQL



嗨,我有一个页面,我试图添加到一个列表,并保存它与视图模型和SQL。你能告诉我我哪里错了吗?

on my Xaml (Page1):

<Entry Margin="5" Text="{Binding Xname}"  Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" FontSize="16" x:Name="entry1" Placeholder="Enter X-rays (6 MV)" PlaceholderColor="White"  BackgroundColor="Gray"/>
<Button Grid.Column="0"
Grid.Row="2"
FontAttributes="Bold"

Command="{Binding AddXrayCommand}"

Text="Add" />
<ListView Grid.Row="3" Grid.ColumnSpan="2" HasUnevenRows="True" Margin="40"
ItemsSource="{Binding energyX}" SelectedItem="{Binding selecteditemX}" 
HorizontalOptions="Start" WidthRequest="150" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="30"></RowDefinition>
<RowDefinition Height="5"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" BackgroundColor="White" Text="{Binding xray}" FontSize="Large" HorizontalTextAlignment="Center" TextColor="Black" WidthRequest="35"/>
<Frame Grid.Row="1" BackgroundColor="Gray"></Frame>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

my Model (Energypage):

public class EnergyX
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string xray { get; set; }
}

和在我的EnergyViewModel:

public class EnergyViewModel
{
public SQLiteConnection conn;
public ObservableCollection<EnergyX> energyX { get; set; } = new ObservableCollection<EnergyX>();
public string Xname { get; set; }
public ICommand AddXrayCommand => new Command(AddX);

public SQLiteConnection GetSQLiteConnection()
{
var fileName = "Energys.db";
var documentPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData);
var path = Path.Combine(documentPath, fileName);
var connection = new SQLiteConnection(path);
return connection;
}

public void AddX()
{
if (Xname != null && Xname.Length > 0)
{
EnergyX XX = new EnergyX();

XX.xray = Xname;

conn = GetSQLiteConnection();
conn.CreateTable<EnergyX>(); 
var dataX = conn.Table<EnergyX>();
var resultX = conn.Insert(XX);


energyX = new ObservableCollection<EnergyX>(conn.Table<EnergyX>().ToList());

}
}
}
}

我确实将我的page1绑定到Energyviewmodel,当我不使用SQL服务时,它可以工作,我认为我的SQL有问题…

我已经调试了视图模型和程序运行到视图模型的末尾,但我的xaml页面列表是空的。

当您的ListView绑定到旧实例

时,这一行将创建一个全新的energyX

实例energyX = new ObservableCollection(conn.Table().ToList());

有两种方法可以修复

选项1,使用INotifyPropertyChanged并在energyX的setter中引发PropertyChanged事件

选项2,不创建energyX的新实例。相反,只需将新项添加到现有实例

energyX.Add(XX);

最新更新