Hi all I have a page that I’m trying to ADD to a list and save it with viewmodel and SQL. but my list is empty Can you tell me where am I wrong??
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; } }
And on my 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()); } } } }
I did bond my page1 to Energyviewmodel, and it works find when I didn’t use SQL service, I think my SQL has problem…
I have debug the viewmodel and program run to the end of the Viewmodel but my xaml page list is empty.
Advertisement
Answer
this line creates a completely new instance of energyX
when your ListView
is bound to the old instance
energyX = new ObservableCollection(conn.Table().ToList());
there are two ways you could fix this
option 1, use INotifyPropertyChanged
and raise a PropertyChanged
event in the setter of energyX
option 2, don’t create a new instance of energyX
. Instead just add the new item to the existing instance
energyX.Add(XX);