How do I hide a TableSection with XAML in Xamarin

2019-09-04 06:33发布

I have been working in Xamarin Forms lately for a project, and I have been using the TableView to show details of a record retrieved from web api. Sometimes, certain details are not present, so I'd like to hide the section that displays the information.

However, I can't find a way to hide the TableSection.

Here's some XAML:

<TableView>
    <TableRoot>

        ...

        <!--Contact info-->
        <TableSection IsVisible="{Binding HasContact}" Title="Contact">

          <!--Contact name-->
          <TextCell Text="{Binding ContactName}" Detail="Primary contact" />

          <!--Phone-->
          <TextCell Text="Phone"
                    Detail="{Binding FormattedContactPhoneNumber}"
                    Command="{Binding BindingContext.DialPhoneCommand, Source={x:Reference MainGrid}}"
                    CommandParameter="{Binding ContactPhoneNumber}"/>


          <!--Email-->
          <TextCell Text="Email"
                    Detail="{Binding ContactEmail}"
                    Command="{Binding BindingContext.SendEmailCommand, Source={x:Reference MainGrid}}"
                    CommandParameter="{Binding ContactEmail}"/>

        </TableSection>
    </TableRoot>
</TableView>

Obviously, the IsVisible property didn't work and throws an exception because it doesn't exist (It is present on other elements like Labels). I also tried using VisualElement.IsVisible which throws an invalid cast exception. So is there any way to hide this section?

If there isn't a way to do it, perhaps I'll need to go down a dirtier path and use separate TableViews (There I can use VisualElement.IsVisible) :(

1条回答
淡お忘
2楼-- · 2019-09-04 07:05

Well you've hit the one drawback of using a TableView, not being able to hide sections dynamically through bindable properties.

In my project I solved this like so:

In the code behind of the page I listen for OnPropertyChanges of the ViewModel that is used as the BindingContext. When the needed boolean changes, I Remove the Cell that is no longer needed in the TableSection. When the Cell is needed again, I Insert it again.

So name all sections and cells and at page start get a hold of those cells that need to change for reference for removing and adding them later.

Small example code

private void OnViewmodelPropertyChanged (object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
    if (e.PropertyName.Equals("IsBioSecurityAvailable", StringComparison.OrdinalIgnoreCase))
    {
        AdjustBioSecurityHeight();
    }
}

private void AdjustBioSecurityHeight()
{
    if (!_viewmodel.IsBioSecurityAvailable && GeneralSection.Contains(BioSecurityViewCell))
        GeneralSection.Remove(BioSecurityViewCell);
}
查看更多
登录 后发表回答