首页 > 解决方案 > Xamarin 表单为标签/列表视图创建创建条件

问题描述

我的应用程序将用户输入组织到各种列表中,以创建一个有组织的购物清单。例如,如果用户输入“apples”,应用程序会将其添加到 FruitList。添加所有项目后,程序将在下一页显示每个列表(因此相似的项目被组合在一起)。我希望第二页只有在其对应的列表包含项目时才为每个类别创建“部分”(当前是一个标签和一个 ListView)。我创建了一个条件,如果列表不包含任何项目,则将标签的 IsVisible 属性设置为 false,但该部分仍占用页面上的空白空间。如果它没有与之关联的项目,我该如何去减小一个部分的大小或完全消除它?下面是来自我的 XAML 视图及其 ViewModel 的一些示例代码。谢谢

看法:

<ContentPage.BindingContext>
        <viewmodels:OrganizedViewModel/>
    </ContentPage.BindingContext>
    
    <ContentPage.Content>
        <StackLayout>
            <Label Text="Fruit" FontSize="Large"
                   IsVisible="{Binding CheckFruit}"/>
            <ListView ItemsSource="{Binding OFruitList}"/>

            <Label Text="Vegetables" FontSize="Large"
                   IsVisible="{Binding CheckVegetable}"/>
            <ListView ItemsSource="{Binding OVegetableList}"/>
        </StackLayout>
    </ContentPage.Content>

视图模型:

class OrganizedViewModel
{
    public ObservableCollection<string> OFruitList { get; set; }
    public ObservableCollection<string> OVegetableList { get; set; }
    public bool CheckFruit { get; set; }
    public bool CheckVegetable { get; set; }

    public OrganizedViewModel()
    {
        OFruitList = new ObservableCollection<string>();
        OVegetableList = new ObservableCollection<string>();
        GetOrganizedList();
        CheckFruit = CheckList(OFruitList);
        CheckVegetable = CheckList(OVegetableList);
    }

    void GetOrganizedList()
    {
        foreach (string value in Categories.FruitList)
        {
            OFruitList.Add(value);
        }
        foreach (string value in Categories.VegetableList)
        {
            OVegetableList.Add(value);
        }
    }

    public bool CheckList(ObservableCollection<string> value)
    {
        if (value.Any())
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

注意:“Categories.FruitList”和“Categories.VegetableList”是上一页填充的字符串列表。

标签: c#xamlxamarin.forms

解决方案


是的,根据您的描述,我们建议您使用 Grouping ListView来实现这一点。

grouping为 ListView 激活时,会为每个组添加一个标题行。要启用分组:

  • 创建列表列表(组列表,每个组都是元素列表)。

  • 将 ListView 设置ItemsSource为该列表。

  • 设置IsGroupingEnabled为真。

  • 设置[GroupDisplayBinding][2]为绑定到用作组标题的组的属性。

  • [可选] 将GroupShortNameBinding设置为绑定到用作组短名称的组的属性。短名称用于跳转列表(iOS 上的右侧列)。

有关更多详细信息,您可以参考文档:https ://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/listview/customizing-list-appearance#grouping 。

此外,您还可以使用Xamarin.Forms CollectionView Grouping来实现这一点。

注:以上两份文件中均包含样本,您可以查看。


推荐阅读