Xamarin.ios:在.Split之后列出跳过的代码的字符串(",")

时间:2018-05-01 10:35:47

标签: ios string listview xamarin.ios mvvmcross

我正在使用Xamarin.ios MvvmCross构建iOS应用。我完成了将字符串转换为.Split(',')的列表。现在,当我运行我的代码,我想在我的应用程序中看到列表。第一次单击某个项时,viewcell将在运行第string[] namesArray = FavoriteContent.ingredients.Split(',');行后跳过该代码。当我回到表格视图并再次推动视单元格时。它将运行代码并显示列表。

我在下面显示的代码位于.Core项目的viewmodel中。我在de views中的de .IOS项目中称之为。

从字符串中创建一个列表并返回它的代码:

private string _ingredients;

    public string Ingredients
    {
        get
        {
            string[] namesArray = FavoriteContent.ingredients.Split(',');
            List<string> namesList = new List<string>(namesArray.Length);
            namesList.AddRange(namesArray);
            namesList.Reverse();
            _ingredients = string.Join("\n", namesList);
            return _ingredients;
        }
    }

这是我将.ios项目中的视图列表调用到viewmodels中的.Core项目的位置

ViewController(第5行我调用列表):

MvxFluentBindingDescriptionSet<DetailFavoriteView, DetailFavoriteViewModel> set = new MvxFluentBindingDescriptionSet<DetailFavoriteView, DetailFavoriteViewModel>(this);
        set.Bind(NameRecipe).To(res => res.FavoriteContent.name);
        set.Bind(DetailImage).For(img => img.Image).To(res => res.FavoriteContent.thumbnail).WithConversion<StringToImageConverter>();
        set.Bind(DescriptionText).To(res => res.FavoriteContent.description);
        set.Bind(IngredientsList).To(res => res.Ingredients);
        set.Bind(ConditionText).To(res => res.Conditions);
        set.Bind(ButtonShopList).To(res => res.PostShopListCommand);
        set.Apply();

1 个答案:

答案 0 :(得分:1)

由于FavoriteContent.ingredientsnull,您将在此行FavoriteContent.ingredients.Split(',');中获得一个异常,该异常将在绑定中捕获,因此您的viewcell将不会显示该内容。第二次,FavoriteContent.ingredients肯定不为空,因此可以更新视单元。

所以我认为你应该在使用FavoriteContent.ingredients做逻辑之前添加一个空检查以避免异常:

private string _ingredients;

public string Ingredients
{
    get
    {
        if (FavoriteContent?.ingredients == null) // IDK if FavoriteContent is a property or a class, I assumed is a property
            return null; // or return string.empty;

        string[] namesArray = FavoriteContent.ingredients.Split(',');
        List<string> namesList = new List<string>(namesArray.Length);
        namesList.AddRange(namesArray);
        namesList.Reverse();
        _ingredients = string.Join("\n", namesList);
        return _ingredients;
    }
}

然后当您加载FavoriteContent.ingredients时,您只需告诉视图使用RaisePropertyChanged刷新该绑定:

// this is the part where you update FavoriteContent.ingredients in your ViewModel so that it is not null
FavoriteContent.ingredients = "my string, my other string, 2, 3";
RaisePropertyChanged(() => Ingredients); // you tell the view Ingredients has changed (make sure you are invoking this in your main thread if not use InvokeOnMainThread(() => RaisePropertyChanged(() => Ingredients));)

HIH