Friday, May 16, 2014

Conditional element in xaml depending on the binding content

Problem:

 I was trying to hide and expose information in xaml form.  The Address should not display if it is empty.
<TextBlock Text="{Binding Path=Address}" />


Solution:

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

Create helper class and reference in the xaml.

 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
    }
}





Source:
http://stackoverflow.com/questions/4450866/conditional-element-in-xaml-depending-on-the-binding-content

No comments:

Post a Comment