zeeshan
zeeshan

Reputation: 55

How to display text for the int values in datagrid cell using mvvm

I am displaying data from a table which contains a column "Status", now this column contains two values 0 and 1 0 => Daily 1 => Monthly by using mvvm structure when i bind my cell text property to returned collection of that table, it displays 0 and 1. what i want that instead of 0, Daily and 1 for Monthly should be displayed. Is there a way to achieve this??

Upvotes: 0

Views: 183

Answers (1)

Tonio
Tonio

Reputation: 743

Yep, you can create a binding converter by implementing interface IValueConverter.

public class IntTextConverter : IValueConverter
{
    // This converts the int object to the string
    // to display 0 => Daily other values => Monthly.
    public object Convert(object value, Type targetType, object parameter,
        System.Globalization.CultureInfo culture)
    {
        // You can test type an value (0 or 1) and throw exception if
        // not in range or type
        var intValue = (int)value;
        // 0 => Daily 1 => Monthly
        return intValue == 0 ? "Daily" : "Monthly";
    }

    // No need to implement converting back on a one-way binding
    // but if you want two way
    public object ConvertBack(object value, Type targetType,
        object parameter, System.Globalization.CultureInfo culture)
    {
        return value == "Daily" ? 0 : 1;
    }
}

And in Xaml, sample binding on textblock :

<Grid.Resources>
   <local:IntTextConverter x:Key="IntTextConverter" />
</Grid.Resources>
...
<TextBlock Text="{Binding Path=Status, Mode=OneWay,
           Converter={StaticResource IntTextConverter}}" />

Upvotes: 1

Related Questions