首页 > 解决方案 > 如何隐藏 Grid 行和 ListView 列,以便看不到任何空白空间?

问题描述

Xamarin Grid 和 ListView 有两个问题。

(1) 在 ListView 中,我有七列。根据条件,需要隐藏第五列和第六列,以使第四列之后没有可见的空白区域。我试图设置 IsVisble=false 但它之间显示空白。

(2) Grid 也有类似的问题。在 ContentView 中,我有十行的 Grid。基于某些条件,我想隐藏第 7 行和第 8 行,以使空白部分折叠起来。用户应该无法查看空行。

如果从代码隐藏我尝试使用下面的代码删除行,我怀疑 .XAML 可能会崩溃,因为行号需要重新排序。

GridView gv = listview.View as GridView;
GridViewColumn cd = gv.Columns[0];
gv.Columns.Remove(cd);
gv.Columns.Add(cd);

标签: xamarinxamarin.forms

解决方案


对于网格问题,请务必使用 Binding 动态设置 RowHeight。因此,只要您想隐藏这些行,就将高度设置为 0。

代码如下所示:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:Test"
             x:Class="Test.MainPage">
    <StackLayout Margin="0,20,0,0">
        <Grid RowSpacing="0" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
            <Grid.RowDefinitions>
                <RowDefinition Height="50" />
                <RowDefinition Height="{Binding RowHeight}" />
                <RowDefinition Height="{Binding RowHeight}" />
                <RowDefinition Height="50" />
                <RowDefinition Height="50" />
            </Grid.RowDefinitions>

            <Label Text="Row 1" Grid.Row="0" HorizontalTextAlignment="Center" />
            <Label Text="Row 2" Grid.Row="1" HorizontalTextAlignment="Center" />
            <Label Text="Row 3" Grid.Row="2" HorizontalTextAlignment="Center" />
            <Label Text="Row 4" Grid.Row="3" HorizontalTextAlignment="Center" />
            <Label Text="Row 5" Grid.Row="4" HorizontalTextAlignment="Center" />
        </Grid>

        <Button Text="Hide rows" Clicked="OnClicked" />
    </StackLayout>
</ContentPage>

public partial class MainPage : ContentPage, INotifyPropertyChanged
{
    private int _rowHeight = 50;
    public int RowHeight
    {
        get => _rowHeight;
        set
        {
            _rowHeight = value;
            OnPropertyChanged();
        }
    }

    public MainPage()
    {
        InitializeComponent();
        BindingContext = this;
    }

    private void OnClicked(object sender, System.EventArgs e)
    {
        RowHeight = 0;
    }
}

推荐阅读