问题描述
我正在关注 Xamarin Forms 项目的教程/示例,其中有一个带有 C# 代码隐藏的视图,绑定到视图模型。但是,我想捕获视图模型中发生的异常并将其显示在警报中或使用任何其他常用技术来显示错误。
这是使用刷新重新加载数据的视图:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MyCompany.App.Views.DashboardPage"
xmlns:vm="clr-namespace:MyCompany.App.viewmodels"
xmlns:dashboard="clr-namespace:MyCompany.App.viewmodels.Dashboard;assembly=MyCompany.App"
Title="{Binding Title}">
...
<RefreshView x:DataType="dashboard:Dashboardviewmodel" Command="{Binding LoadItemsCommand}" IsRefreshing="{Binding IsBusy,Mode=TwoWay}">
... content
</RefreshView>
</ContentPage>
public partial class DashboardPage : ContentPage
{
Dashboardviewmodel _viewmodel;
public DashboardPage()
{
InitializeComponent();
BindingContext = _viewmodel = new Dashboardviewmodel();
}
protected override void OnAppearing()
{
base.OnAppearing();
_viewmodel.OnAppearing();
}
}
最后是加载发生的视图模型。它继承自教程中提供的 Baseviewmodel。
public class Dashboardviewmodel : Baseviewmodel
{
private DashboardItemviewmodel _selectedItem;
public ObservableCollection<DashboardItemviewmodel> Items { get; }
public Command LoadItemsCommand { get; }
public Command<DashboardItemviewmodel> ItemTapped { get; }
public Dashboardviewmodel()
{
Title = "Dashboard";
Items = new ObservableCollection<DashboardItemviewmodel>();
LoadItemsCommand = new Command(async () => await ExecuteLoadItemsCommand());
ItemTapped = new Command<DashboardItemviewmodel>(OnItemSelected);
}
async Task ExecuteLoadItemsCommand()
{
IsBusy = true;
try
{
Items.Clear();
var items = await GetItems();
foreach (var item in items)
{
Items.Add(item);
}
}
finally
{
IsBusy = false;
}
}
private static async Task<List<DashboardItemviewmodel>> GetItems()
{
// Where errors happen
return items;
}
public void OnAppearing()
{
IsBusy = true;
SelectedItem = null;
}
public DashboardItemviewmodel SelectedItem
{
get => _selectedItem;
set
{
SetProperty(ref _selectedItem,value);
OnItemSelected(value);
}
}
async void OnItemSelected(DashboardItemviewmodel item)
{
if (item == null || item.Uri.IsNotSet())
return;
await Shell.Current.GoToAsync(item.Uri);
}
}
我在 ContentPage 中看不到任何用于捕获异常的可覆盖方法。捕获异常并将其显示在警报中的最佳方法是什么?
解决方法
我不确定你到底想要什么,但为了捕捉错误,我使用了 try/catch 方法。
df %>% unite('W',starts_with('w'),sep = '=',na.rm = T,remove = T) %>%
separate(W,into = paste0('w',seq_len(1 + max(str_count(.$W,'=')))),fill = 'left',sep = '=')
size w1 w2 w3 w4
1 2 <NA> <NA> come on
2 2 <NA> <NA> why that
3 3 <NA> er i can
4 3 <NA> well not today
5 4 she 's going on
6 4 well thanks they can
7 3 <NA> er super cool
8 3 <NA> well she can