2

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?

Bart
  • 9,925
  • 7
  • 47
  • 64
ThePeter
  • 883
  • 1
  • 7
  • 15
  • You should use a [Converter](https://msdn.microsoft.com/library/windows/apps/windows.ui.xaml.data.binding.converter). – tao Aug 09 '16 at 03:23

1 Answers1

1

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>