Skip to content

Instantly share code, notes, and snippets.

@LGM-AdrianHum
Last active October 29, 2015 23:23
Show Gist options
  • Save LGM-AdrianHum/4dfd51f9af3bf7ccd2bd to your computer and use it in GitHub Desktop.
Save LGM-AdrianHum/4dfd51f9af3bf7ccd2bd to your computer and use it in GitHub Desktop.
A simple ValueConverter that can change visibility when a text value that is bound to it is null or empty

#Using a ValueConverter to make a control visible when there is string content.

Sometimes it is useful to have a control completely disappear when it or another value has no text value. In this case, it is handy to be able to bind the control to the string value, and trigger a visibility change when it has not value. You can also achieve this by using a data trigger on a style.

// Created Date: 2015-10-13 12:36 PM
// Modified Date: 2015-10-13 12:36 PM
#region Using Directives
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
#endregion
public class TextToVisibility : IValueConverter
{
#region Implementation of IValueConverter
/// <summary>
/// Converts a value.
/// </summary>
/// <returns>
/// A converted value. If the method returns null, the valid null value is used.
/// </returns>
/// <param name="value">The value produced by the binding source.</param>
/// <param name="targetType">The type of the binding target property.</param>
/// <param name="parameter">The converter parameter to use.</param>
/// <param name="culture">The culture to use in the converter.</param>
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return string.IsNullOrEmpty(value as string) ? Visibility.Collapsed : Visibility.Visible;
}
/// <summary>
/// Converts a value.
/// </summary>
/// <returns>
/// A converted value. If the method returns null, the valid null value is used.
/// </returns>
/// <param name="value">The value that is produced by the binding target.</param>
/// <param name="targetType">The type to convert to.</param>
/// <param name="parameter">The converter parameter to use.</param>
/// <param name="culture">The culture to use in the converter.</param>
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment