2

As I mentioned in a recent question on how to show strings with carriage returns in a gridview, I also wondered about how to format this particular string differently, on the fly.

The string coming back from the database has carriage returns. It is then directly bound to a GridViewColumn like this:

<GridViewColumn Width="365" Header="Desc" DisplayMemberBinding="{Binding desc}" />

Say I want to remove those carriage returns, using a String.Replace, but without altering the DataTable the gridview is bound to.

I used to do something similar in ASP.net with the Repeater.OnItemDataBound method, applying formatting or the like.

Community
  • 1
  • 1
jmlumpkin
  • 922
  • 2
  • 14
  • 34

2 Answers2

3

You would need to make a value converter:

[ValueConversion(typeof(string), typeof(string))]
public class ReplaceCarriageReturnConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value as string == null ? string.Empty : (value as string).Replace("\r", " - "); ;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Declare your converter:

<local:ReplaceCarriageReturnConverter x:Key="ReplaceCarriageReturnConverter"/>

Modify your binding:

<GridViewColumn Width="365" Header="Desc" DisplayMemberBinding="{Binding desc, Converter={StaticResource ReplaceCarriageReturnConverter}}" />
Dylan
  • 2,392
  • 6
  • 26
  • 34
0

You can use a ValueConverter on your binding. See the documentation on MSDN here:

http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx

Basically, you create a class implementing IValueConverter, and in the Convert method, you convert the string just as you like (remove carriage returns in your case).

If that converter is added to your binding (see link for details), your GridViewColumn will display the value returned by your ValueConverter.
Because the value is only modified before it is displayed, your DataTable will not get modified.

Here is a tuturial on using ValueConverters:

http://wpftutorial.net/ValueConverters.html

Botz3000
  • 39,020
  • 8
  • 103
  • 127