NumToBoolConverter - A simple IValueConverter implementation

By Anoop Madhusudanan

Vote on HN
Some 'Beginner's' stuff. One good thing about WPF is the ability to specify custom converters, when you do the binding.

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}}"/>

1 comment:

  1. Hello,

    Firstly, I liked your Idea,I am working in silverLight 3(MVVM).

    Can you please, help me to implement over there.

    Thanks,
    gauthamshetty86@gmail.com

    ReplyDelete

Please keep your comments clean.

© 2012. All Rights Reserved. Amazedsaint.com