Learn About Converters In WPF

What are Converters?

Converters are basically a medium to convert values in one form to another form.

Converters usually implement IValueConverter interface, which contain two methods, Convert() and ConvertBack().

Let’s dive into a real life example.

The requirement

We have a window with a checkbox and a button. We want the button to be disabled and the visibility collapsed once the checkbox is clicked.

So, how do we achieve this?

  1. Create a BoolToVisibilityConverter that converts the bool value into a type of Visibility enum.
  2. Create a InvertBoolConverter so that IsEnabled property of the button is inverse of that of the IsChecked property of the checkbox.

    WPF

    WPF

Sounding complex? Let’s have a look at the code. It is easy, trust me.

Create the BoolToVisibilityConverter class

  1. using System;  
  2. usingGlobalization;  
  3. usingWindows;  
  4. usingWindows.Data;  
  5. namespace CSharpCorner {  
  6.     public class BoolToVisibilityConverter: IValueConverter {  
  7.         public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {  
  8.             return value != null && (bool) value ? Visibility.Collapsed : Visibility.Visible;  
  9.         }  
  10.         public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {  
  11.             throw new NotImplementedException();  
  12.         }  
  13.     }  
  14. }  

Why the above code? 

The above code converts ‘true’ value to Visibility Collapsed and ‘false’ value to Visibility Visible.

Create the InvertBoolConverter class

  1. using System;  
  2. usingGlobalization;  
  3. usingWindows.Data;  
  4. namespace CSharpCorner {  
  5.     public class InvertBoolConverter: IValueConverter {  
  6.         public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {  
  7.             return value == null || !(bool) value;  
  8.         }  
  9.         public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {  
  10.             throw new NotImplementedException();  
  11.         }  
  12.     }  
  13. }  

Why the above code? 

The above code converts ‘true’ value to ‘false’ and a ‘false’ value to ‘true’.

This is done to align the IsChecked Property of the checkbox to the IsEnabled property of the button. Both are inversely proportional to one another. (If checkbox is checked, the button is disabled and vice versa).

Create the MainWindowViewModel:

  1. usingComponentModel;  
  2. usingRuntime.CompilerServices;  
  3. namespace CSharpCorner {  
  4.     public class MainWindowViewModel: ViewModelBase {  
  5.         private bool isChecked;  
  6.         public MainWindowViewModel() {  
  7.             this.IsEnabled = true;  
  8.         }  
  9.         public bool IsChecked {  
  10.             get => isChecked;  
  11.             set {  
  12.                 this.isChecked = value;  
  13.                 this.OnPropertyChanged();  
  14.             }  
  15.         }  
  16.         public bool IsEnabled {  
  17.             get;  
  18.         }  
  19.     }  
  20.     public class ViewModelBase: INotifyPropertyChanged {  
  21.         public event PropertyChangedEventHandler PropertyChanged;  
  22.         protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) {  
  23.             PropertyChanged ? .Invoke(thisnew PropertyChangedEventArgs(propertyName));  
  24.         }  
  25.     }  
  26. }  

Create the XAML View

  1. <Window x:Class="CSharpCorner.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:CSharpCorner" mc:Ignorable="d" Title="Using Converters" Height="450" Width="800">  
  2.     <!--Set the data context to the MainWindowViewModel-->  
  3.     <Window.DataContext>  
  4.         <local:MainWindowViewModel /> </Window.DataContext>  
  5.     <!--Define the converters in the resources-->  
  6.     <Window.Resources>  
  7.         <local:BoolToVisibilityConverter x:Key="BoolConverter" />  
  8.         <local:InvertBoolConverter x:Key="InvertBoolConverter" /> </Window.Resources>  
  9.     <Grid>  
  10.         <Grid.Resources>  
  11.             <!--Define the style and trigger conditions as to when you want them fired. -->  
  12.             <Style x:Key="ButtonStyle" TargetType="Button">  
  13.                 <Style.Triggers><Trigger Property="IsEnabled" Value="False"><Setter Property="Visibility" Value="Collapsed"/></Trigger></Style.Triggers>  
  14.             </Style>  
  15.         </Grid.Resources>  
  16.         <Grid.RowDefinitions>  
  17.             <RowDefinition Height="50" />  
  18.             <RowDefinition /> </Grid.RowDefinitions>  
  19.         <Border Grid.Row="0" BorderBrush="Black" BorderThickness="1" Visibility="{Binding Path=IsChecked, Converter={StaticResource BoolConverter}}" />  
  20.         <Grid Grid.Row="0">  
  21.             <Grid.ColumnDefinitions>  
  22.                 <ColumnDefinition Width="150" />  
  23.                 <ColumnDefinition Width="500" />  
  24.                 <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions>  
  25.             <Button Grid.Column="0" Content="Back" IsEnabled="{Binding IsChecked, Converter={StaticResource InvertBoolConverter}}" Style="{StaticResource ButtonStyle}"></Button> </Grid>  
  26.         <CheckBox x:Name="checkBox" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Center" Content="Disable Buttons" IsChecked="{Binding IsChecked, Mode=TwoWay}" /> </Grid>  
  27. </Window>  

So, we managed to hide the button and the border when the button was in disabled state using Converters. Not that difficult, was it?