Number To Bool Converter

Here is a simple IValueConverter implementation, to convert an int value (1 or 0) to corresponding bool values (true or false).

Useful if you want to bind a check box or something to a property of numeric type.

 
public class NumToBoolConverter : IValueConverter
    {

        #region IValueConverter Members

        public object Convert(object value, Type targetType, 
            object parameter, System.Globalization.CultureInfo culture)
        {
            if (value!=null && value is int )
            {
                var val = (int)value;
                return (val==0) ? false : true;
            }
            return null;

        }

        public object ConvertBack(object value, Type targetType, 
            object parameter, System.Globalization.CultureInfo culture)
        {
            if (value!=null && value is bool )
            {
                var val = (bool)value;
                return val ? 1 : 0;
            }
            return null;
        }

        #endregion
    }

Now, to do the binding in Xaml, you can just create a resource,

 

<Window.Resources >
        <local:NumToBoolConverter x:Key="IntConverter"/>
    </Window.Resources>

And then do the binding. Simple and easy.

 

<CheckBox Name="chkBox" 
IsChecked="{Binding Path=IntProperty,Mode=TwoWay, 
Converter={StaticResource IntConverter}}"/>

 

Advertisements
By Sriramjithendra Posted in WPF

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s