Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: Binding Visibility by string contents

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?

like image 595
Jonathan Allen Avatar asked Jan 23 '10 10:01

Jonathan Allen


4 Answers

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;
    }
}
like image 53
Markus Hütter Avatar answered Nov 12 '22 11:11

Markus Hütter


If you are inside a (Data-)Template you can use Triggers for that.

Otherwise, the MVVM-Pattern or a ValueConverter will help you.

like image 38
Matthias Avatar answered Nov 12 '22 12:11

Matthias


By putting an extra property in your viewmodel that you can bind the Visibility attribute to:

public class ViewModel
{
   public string InstanceName {...}
   public Visibility InstanceVisibility 
   { 
      get 
      {
           return String.IsNullOrEmpty(InstanceName) ? Visibility.Collapsed : Visibility.Visible;
      }
}
like image 2
Peter Lillevold Avatar answered Nov 12 '22 10:11

Peter Lillevold


<TextBlock Text="{Binding Path=InstanceName},FallbackValue={x:Null}"></TextBlock>

Then add a DataTrigger to check the value is null and change visibility using Setter. This is the simple method which iam using.

like image 1
Kishore Kumar Avatar answered Nov 12 '22 12:11

Kishore Kumar