DotNet Mirror
  DNM facebook   DNM Google+   DNM Twitter   

WPF Visibility Converter example using IValueConverter

By Ashok Nalam on 26 Nov 2013 | Category: WPF | Tagged: conversion converter .NET 
WPF Visibility Converter example using IValueConverter
  Discuss Add Comment   |  
Add rating Rate this resource   

Introduction:

Generally we need to set Visibility property for WPF control based on bit (True/False) value from database. The following snippet shows how to convert bool value to Visibility and vice-versa using System.Windows.Data.IValueConverter interface .

WPF control uses Visibility attribute to show/hide/collapse the control. Visibility is an enumeration from System.Windows namespace.
Visibility enumeration values are
  • Visible - To display control.
  • Collapsed - Do not display the control and do not reserve space for it in the layout.
  • Hidden - Do not display the control, but reserve space for the control in the layout.

Note: Mostly we use Visible/Collapsed values so following example converts True to Visible and False to Collapsed. If you want to change False to Hidden just change Visibility.Collapsed to Visibility.Hidden in Convert method.

VisibilityConverter.cs:

using System.Windows;
using System.Windows.Data;
namespace DotNetMirror.Converters
{
    public class VisibilityConverter : IValueConverter
    {
        public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            bool visibility = false;
            if (value is bool)
            {
                visibility = (bool)value;  
            }
            return visibility ? Visibility.Visible : Visibility.Collapsed;
        }
        public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Visibility visibility = (Visibility)value;
            return (visibility == Visibility.Visible);
        }
    }
}

XAML:

<Window
    xmlns:converter="clr-namespace:DotNetMirror.Converters"
</Window>
<Window.Resources>
    <converter:VisibilityConverter x:Key="VisibilityConverter" />
</Window.Resources>
<Label Content="VisibilityConverter" Visibility="{ Binding IsVisible, Converter={StaticResource VisibilityConverter}}" />
Binding IsVisible  - Bool value from DataContext.
  Discuss Add Comment    
Add rating Rate this resource   
About the Contributor
Member Since : 10 Dec 2012
Member Points (Level) : 9626  (Professional)
Location : INDIA
Home Page : http://dotnetmirror.com
About : I am admin of this site.
Rate this resource
 
Add your Comment
Name Email WebSite
Captcha Refresh


Comments (0)
No comments found, click here to add comment.
 
cheap jordans|wholesale air max|wholesale jordans|wholesale jewelry|wholesale jerseys