17

Is it possible to display this TextBlock, only if the Address.Length > 0 ? I'd like to do this directly into the xaml, I know I could put all my controls programmatically

 <TextBlock Text="{Binding Path=Address}" />
Donut
  • 110,061
  • 20
  • 134
  • 146
Thomas Joulin
  • 6,590
  • 9
  • 53
  • 88

3 Answers3

22

Basically, you're going to need to write an IValueConverter so that you can bind the Visibility property of your TextBox to either the Address field, or a new field that you create.

If you bind to the Address field, here's how the binding might look like::

<TextBlock Text="{Binding Path=Address}"
    Visibility="{Binding Path=Address, Converter={StaticResource StringLengthVisibilityConverter}}" />

And then StringLengthVisiblityConverter could look something like this:

public class StringLengthVisiblityConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null || value.ToString().Length == 0)
        {
            return Visibility.Collapsed;
        }
        else
        {
            return Visibility.Visible;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // Don't need to implement this
    }
}

Then you'd just need to add your converter as a resource, using syntax like this (where src is mapped to the namespace where the converter is defined):

<src:StringLengthVisiblityConverter x:Key="StringLengthVisiblityConverter" />
Donut
  • 110,061
  • 20
  • 134
  • 146
  • The XAML is missing a curly bracket, if I spotted that correctly, no? – Tobias Oct 08 '18 at 21:09
  • @Tobias I think you're right, although in full disclosure I haven't done anything with XAML in years so I'm a bit rusty. I've updated the answer, however - thanks for pointing it out. – Donut Oct 09 '18 at 15:16
8

I would do this with another boolean property called HasAddress which returns Address.Length > 0.

<!-- In some resources section -->
<BooleanToVisibilityConverter x:Key="Bool2VisibilityConverter" />

<TextBlock 
  Text="{Binding Address}" 
  Visibility="{Binding HasAddress, Converter={StaticResource Bool2VisibilityConverter}}" 
/>

You should also remember to notify the property change for HasAddress in the setter of Address.

devdigital
  • 34,151
  • 9
  • 98
  • 120
3

You can create a StringToVisibility converter.

It will return Visibility.Visible if bound string is not null or empty and Visibility.Collapsed if it is.

Use this converter while binding Address with Visibility property of your TextBlock.

Example:

<TextBlock Text="{Binding Path=Address}" Visibility="{Binding Address, Converter={StaticResource StringToVisibilityConverter}}" />
Community
  • 1
  • 1
decyclone
  • 30,394
  • 6
  • 63
  • 80