WPF MVVM Hide Button using BooleanToVisibilityConverter in C#

Updated on     Kisan Patel

Problem:

How to Hide Button using BooleanToVisibilityConverter in WPF?
WPF MVVM Hide Button using BooleanToVisibilityConverter in C#
Binding a Button Visibility to bool value in ViewModel
Bind visibility property to a variable

Solution

First add BooleanVisibilityConverter.cs class and inherit IValueConverter interface as shown in below code:

using System.Windows.Data;

namespace Payroll.Desktop.Utility
{
    public class BooleanVisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            // Call ButtonTextConverter here and return the result
            if ((bool)value == true)
            {
                return "Visible";
            }
            else
            {
                return "Hidden";
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

Next, open App.xaml file and add Key as shown in below code:

<Application .....
 xmlns:utility="clr-namespace:Payroll.Desktop.Utility"
 StartupUri="MainWindow.xaml">
    <Application.Resources>
       <ResourceDictionary>
           <utility:ButtonVisibilityConverter x:Key="ButtonToVis" />
       </ResourceDictionary>
    </Application.Resources>
 
</Application>
Visibility="{Binding PropertyName, Converter={StaticResource BooleanVisibilityConverter}, FallbackValue=Hidden}"

Source:
https://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter(v=vs.110).aspx
http://stackoverflow.com/questions/20570148/wpf-mvvm-hiding-button-using-booleantovisibilityconverter


WPF