c# - 在搜索栏中键入后使用后退箭头时未填充列表视图
问题描述
我有一个带有搜索栏的列表视图,我可以在列表视图中搜索一个项目并单击该项目并导航到该项目的详细信息,但是当我单击后退箭头时,我的 HttpResponseMessage 上出现 System.NullReferenceException。有人可以告诉我我可能做错了什么。如果搜索栏为空,则可以正常工作。
视图模型
private async Task GetProjects(string email)
{
IsBusy = true;
ProjectList = new ObservableCollection<ProjectModel>();
using (HttpClient client = new HttpClient())
{
try
{
using (HttpResponseMessage response = await client.GetAsync("http://example/api/GetProject/email=" + email + "/"))
{
if (response.IsSuccessStatusCode)
{
using (HttpContent content = response.Content)
{
var textresponse = await content.ReadAsStringAsync();
var json = JsonConvert.DeserializeObject<List<ProjectModel>>(textresponse);
foreach (var t in json)
{
if (t.pjtIsActive == 1)
{
ProjectList.Add(new ProjectModel
{
..............
});
}
}
IsBusy = false;
}
}
else
{
}
}
}
catch (Exception)
{
IsBusy = false;
}
}
}
private ICommand _searchCommand;
public ICommand SearchCommand
{
get
{
return _searchCommand ?? (_searchCommand = new Command<string>
(async (text) =>
{
if (text.Length >= 1)
{
ProjectList.Clear();
await GetProjects(EmailAddress);
var projectSearch = ProjectList.Where(c => c.pjtName.ToLower().StartsWith(text.ToLower()) || c.ClientName.ToLower().StartsWith(text.ToLower()) || c.ContractorName.ToLower().StartsWith(text.ToLower()) || c.pjtNumber.ToLower().StartsWith(text.ToLower())).ToList();
ProjectList.Clear();
foreach (var item in projectSearch)
ProjectList.Add(item);
}
else
{
GetProjects(EmailAddress);
}
}));
}
}
private ICommand _projectDetailsCommand;
public ICommand ProjectDetailsCommand=> _projectDetailsCommand?? (_projectDetailsCommand= new Command(async (object obj) => {
var item = (obj as ProjectModel);
ProjectModel project = new ProjectModel();
...........
Navigation.PushAsync(new Project_Details(project));
}));
内容页
protected override void OnAppearing()
{
BindingContext = new Project_View_ViewModel(Navigation);
base.OnAppearing();
}
解决方案
您应该在构造函数中调用绑定上下文并在 OnAppearing 中刷新所需的数据,
private Project_View_ViewModel bindingv;
public Project_View()
{
try
{
InitializeComponent();
bindingv = new Project_View_ViewModel(Navigation);
BindingContext = bindingv;
}
catch (Exception ex)
{
Logger.Log(ex);
}
}
protected async override void OnAppearing()
{
base.OnAppearing();
try
{
if (bindingv != null)
{
await bindingv.GetProjects();
}
}
catch (Exception ex)
{
Logger.Log(ex);
}
}
推荐阅读
- java - Flink 与 Kafka 集成
- python - BigQuery TypeError:to_pandas() 得到了一个意外的关键字参数“timestamp_as_object”
- python - 如何在元组中复制元素n次
- base64 - 如何复制粘贴 Google 的 SSO 证书以连接 dex?
- javascript - mapkit.js:如何实现注解选中和取消选中时的放大缩小
- c++ - MPI_Isend/MPI_Irecv 在什么条件下等待其关联的完成调用 (MPI_Wait/MPI_Test) 开始数据传输?
- performance - Haskell 中的性能改进
- python - 无论行顺序如何,比较不同行的 DataFrame
- python-3.x - Python 中另一个 API 请求(相同 API)中的 API 请求
- javascript - 自定义 Bootstrap-Vue 复选框组件