How do I get a WPF listview to format a byte array as a comma-delimited string?

c#, data-binding, datatemplate, listview, wpf

Solution

I would suggest using a ValueConverter:

[ValueConversion(typeof(byte []), typeof(string))]
public class ByteArrayConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        byte [] bytes = (byte [])value;
        StringBuilder sb = new StringBuilder(100);
        for (int x = 0; x<bytes.Length; x++)
        {
            sb.Append(bytes[x].ToString()).Append(" ");
        }
        return sb.ToString();
    }

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

    #endregion
}

In your xaml, you'd add it to your binding like this:

<Window.Resources>
    <local:ByteArrayConverter x:Key="byteArrayConverter"/>
</Window.Resources>

...

"{Binding ByteArrayProperty, Converter={StaticResource byteArrayConverter}}"

Problem

I'm trying to bind some data to a WPF listview. One of the properties of my data type is of type `byte[]` and I'd like it to be shown as a comma-delimited string, so for example `{ 12, 54 }` would be shown as `12, 54` rather than as `Byte[] Array`. I think I want to make a custom `DataTemplate` but I'm not sure. Is that the best way? If so, how do I do it? If not, what is the best way? EDIT: I only want to use this for one column - the other properties are displayed fine as they are.

Original source