在下面的代码中,我绑定记录形成了一个视图模型,它使用了一个 observablecollection,我也提高了 inotifypropertychange,现在我有一个按钮设置,它使用 navigation.pushasync 方法转到一个新页面,在那里我更新数据库记录,我在这个新页面中创建了一个列表视图,并使用此处显示的相同绑定来绑定记录,每当我添加它更新的内容时,但如果我按下后退按钮并返回到这个 EntryTabPage 绑定不会更新,它只会更新如果我完全关闭应用程序并重新启动它,则会显示数据。
我希望更新此列表视图,不知道该怎么做,我尝试使用 onappearing 并输入 Listviewname.itemssource=Records; 但这显示了一个错误“这在当前上下文中不存在”任何正确方向的帮助将不胜感激。
注意:绑定在除标签页之外的其他地方工作。这是 Hierarchy TabbedPage->ContentPage->StackLayout->ListView(在此列表视图中,绑定不会更新。
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Bunk_Master.EntryPageTab1"
Title="Default">
<StackLayout x:Name="stacklayout">
<ListView ItemsSource="{Binding Records}"
x:Name="classListView">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding}">
</TextCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Button Text="new"
x:Name="addclassbutton">
</Button>
</StackLayout>
namespace Bunk_Master
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class EntryPageTab1 : ContentPage
{
public EntryPageTab1()
{
InitializeComponent();
BindingContext = new ClassViewModel();
addclassbutton.Clicked += async (object sender, EventArgs e) =>
{
await this.Navigation.PushAsync(new AddClass());
};
}
protected override void OnAppearing()
{
base.OnAppearing();
}
}
}
这是 ViewModel
namespace Bunk_Master
{
public class ClassViewModel : BaseViewModel
{
readonly Database db;
public string classname { get; set; }
// public int absentnos { get; set; }
// public int presentnos { get; set; }
public ICommand AddCommand { get; set; }
public ICommand DeleteCommand { get; set; }
public ObservableCollection<string> Records { get; set; }
public ClassViewModel()
{
AddCommand = new Command(Add);
DeleteCommand = new Command(Delete);
db = new Database("classdb");
db.CreateTable<ClassModel>();
Records = new ObservableCollection<string>();
ShowAllRecords();
}
void Add()
{
var record = new ClassModel
{
classname = classname,
//absentnum = absentnos,
//presentnum = presentnos
};
db.SaveItem(record);
Records.Add(record.ToString());
RaisePropertyChanged(nameof(Records));
ClearForm();
}
private void Delete(object obj)
{
throw new NotImplementedException();
}
void ClearForm()
{
classname = string.Empty;
RaisePropertyChanged(nameof(classname));
}
void ShowAllRecords()
{
Records.Clear();
var classdb = db.GetItems<ClassModel>();
foreach (var classmodel in classdb)
{
Records.Add(classmodel.ToString());
}
}
}
}
这是我实现 Inotifypropertychange 的地方
namespace Bunk_Master
{
public class BaseViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged([CallerMemberName] string propertyName = "")
{
var handler = PropertyChanged;
if (handler == null) return;
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}