silverlightdata-bindingxamlconvertersnumeric-conversion

Silverlight XAML Binding -- Decimal to Double


I've got some Columns in a DataGridView that have their Binding property set to something like the following:

Binding="{Binding NetPrice}"

The problem is that this NetPrice field is a Decimal type and I would like to convert it to Double inside the DataGrid.

Is there some way to do this?


Solution

  • I would create a Converter. A converter takes one variable and "converts" it to another.

    There are a lot of resources for creating converters. They are also easy to implement in c# and use in xaml.

    Your converter could look similar to this:

    public class DecimalToDoubleConverter : IValueConverter   
    {   
        public object Convert( 
            object value,   
            Type targetType,   
            object parameter,   
            CultureInfo culture)   
        {   
            decimal visibility = (decimal)value;
            return (double)visibility;
        }   
    
        public object ConvertBack(   
            object value,   
            Type targetType,   
            object parameter,   
            CultureInfo culture)   
        {
            throw new NotImplementedException("I'm really not here"); 
        }   
    }
    

    Once you've created your converter, you will need to tell your xaml file to include it like this:

    in your namespaces (at the very top of your xaml), include it like so:

    xmlns:converters="clr-namespace:ClassLibraryName;assembly=ClassLibraryName"
    

    Then declare a static resource, like so:

    <Grid.Resources>
        <converters:DecimalToDoubleConverter x:Key="DecimalToDoubleConverter" />
    </Grid.Resources>  
    

    Then add it to your binding like this:

    Binding ="{Binding Path=NetPrice, Converter={StaticResource DecimalToDoubleConverter}"