Search code examples
listviewhideuwpbindno-data

How to collapse a data bound control in UWP when there is no data in the field


I am working on a UWP app that has data bound in a ListView. I have been trying to find a way to collapse (hide) a control when there is no data. For example, i made a simple version of what i am doing:

<ListView Name="lvwMaster" ItemsSource="{x:Bind CollectionOfPeople}">
    <ListView.ItemTemplate>
        <DataTemplate x:DataType="data:Person">
            <StackPanel Name="pnlOnePerson" Margin="10">
                <TextBlock Name="lblFirstName" Text="{x:Bind FirstName}" />
                <TextBlock Name="lblMiddleName" Text="{x:Bind MiddleName}" Height="Auto" />
                <TextBlock Name="lblLastName" Text="{x:Bind LastName}" />
                <TextBlock Name="lblBirthDate" Text="{x:Bind BirthDate}" />
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Since not everyone has a middle name, i want the middle name field to be hidden when it is empty.

example of what it looks like when run

Any suggestions on how i might be able to hide the middle name field when the person doesn't have a middle name?


Solution

  • Use a Value Converter

    class TextToVisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            string name = System.Convert.ToString(value);
            if (string.IsNullOrEmpty(name))
            {
                return Visibility.Collapsed;
            }
            return Visibility.Visible;        }
    
        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }
    

    define the Converter as a static resource inside the page.

    <Page.Resources> 
      <local:TextToVisibilityConverter x:Name="ConverterNameHere"/> 
    </Page.Resources>
    

    in your data template use it like this,

    <DataTemplate x:DataType="data:Person">
                        <StackPanel Name="pnlOnePerson" Margin="10">
                            <TextBlock Name="lblFirstName" Text="{x:Bind FirstName}" />
                            <TextBlock Name="lblMiddleName" Text="{x:Bind MiddleName}" Height="Auto" Visibility ="{Binding path=Text, ElementName="lblMiddleName" Converter={StaticResource ConverterNameHere}}" />
                            <TextBlock Name="lblLastName" Text="{x:Bind LastName}" />
                            <TextBlock Name="lblBirthDate" Text="{x:Bind BirthDate}" />
                        </StackPanel>
                    </DataTemplate>