我有两个页面...主页包含一个列表视图和一个按钮,该按钮弹出一个页面(第二页)以插入到sqlite。所以我有一个load()方法,该方法从sq lite数据库获取数据并将其加载到列表视图。我在Main Page构造函数中以及每次插入后的第二页中都调用此方法。
主页中的加载方法
public void load_Records()
{
ObservableCollection<MyChickenModal> chickens_record;
using (var db = new DataAccess())
{
chickens_record = new ObservableCollection<MyChickenModal>(db.GetAllData());
}
DisplayAlert("Alert", chickens_record.Count.ToString(), "OK");
record_lst.ItemsSource = chickens_record;
}
和第二页
public partial class NewChicksPopUp : Rg.Plugins.Popup.Pages.PopupPage
{
public DateTime selected_date = DateTime.Today.Date;
MainPage mainP;
public NewChicksPopUp (MainPage mainP)
{
InitializeComponent ();
this.mainP = mainP;
}
private void chickenSubmit_btn_Clicked(object o, EventArgs e)
{
string record_name = record_name_txt.Text;
using (var db = new DataAccess())
{
if (!string.IsNullOrEmpty(record_name) && !string.IsNullOrWhiteSpace(record_name) && selected_date!=null)
{
db.InsertChicken(new MyChickenModal { Id = 1, Name = record_name, Age = 0, Weight = 0, StartDate = selected_date.ToString("dd/MM/yyyy") });
}
}
//************ HERE I CALL THE LOAD METHOD FROM MAIN PAGE********
mainP.load_Records();
PopupNavigation.Instance.PopAsync(true);
}
private void closePop_btn_Clicked(object o, EventArgs e)
{
PopupNavigation.Instance.PopAsync(true);
}
private void record_date_picker_DateSelected(object sender , DateChangedEventArgs e)
{
selected_date = e.NewDate.Date;
}
}
问题在于,load方法在构造函数中可以正常工作,并且可以将数据加载到列表视图中.....当我在插入后从另一个页面调用load方法时,该方法很好,因为会显示警报消息,但列表确实可以完全没有改变。 注意:插入是可以的,因为当我重新运行该应用程序时,会出现新记录
答案 0 :(得分:0)
尝试一下:
public void load_Records()
{
ObservableCollection<MyChickenModal> chickens_record;
using (var db = new DataAccess())
{
chickens_record = new ObservableCollection<MyChickenModal>(db.GetAllData());
}
DisplayAlert("Alert", chickens_record.Count.ToString(), "OK");
// Setting the ItemsSource to null will refresh the ListView
record_lst.ItemsSource = null;
record_lst.ItemsSource = chickens_record;
}
这是/一种解决方法,在单声道的早期就达到了效果。我不确定这是否仍然有效,但值得尝试
正如我已经提到的,以MVVM方式进行操作。添加一个名为xxxViewModel的新类:
public class YourPageViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
private ObservableCollection<MyChickenModal> _chicken;
public ObservableCollection<MyChickenModal> Chicken
{
get => _chicken;
set
{
_chicken = value;
PropertyChanged(this, new PropertyChangedEventArgs(nameof(Chicken)));
}
}
public void LoadRecords()
{
var collection = new ObservableCollection<MyChickenModal>();
using (var db = new DataAccess())
{
var allData = db.GetAllData();
collection = new ObservableCollection<MyChickenModal>(allData);
}
DisplayAlert("Alert", chickens_record.Count.ToString(), "OK");
Chicken = collection;
}
}
您的Xaml代码背后:
public partial class YourPage
{
public YourPage ()
{
InitializeComponent ();
// Set the ViewModel
this.BindingContext = new YourPageViewModel();
}
}
然后在您的Xaml中执行以下操作:
<ListView ... ItemsSource="{Binding Chicken}" .../>