WPF: Binding Visibility by string contents

Jonathan Allen picture Jonathan Allen · Jan 23, 2010 · Viewed 22k times · Source

Ok, so here is my XAML:

<TextBlock Text="{Binding Path=InstanceName}"></TextBlock>

If InstanceName is null or an empty string, I want Visibility="Collapsed". Otherwise I want Visibility="Visible". How would I do that?

Answer

Markus H&#252;tter picture Markus Hütter · Jan 23, 2010

You could use a ValueConverter:

<TextBlock 
     Visibility="{Binding InstanceName, Converter={local:StringNullOrEmptyToVisibilityConverter}}" 
     Text="{Binding InstanceName}"/>

with the following codebehind:

public class StringNullOrEmptyToVisibilityConverter : System.Windows.Markup.MarkupExtension, IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return string.IsNullOrEmpty(value as string) 
            ? Visibility.Collapsed : Visibility.Visible;
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return null;
    }
    public override object ProvideValue(IServiceProvider serviceProvider)
    {            
        return this;
    }
}