tags:

views:

23

answers:

1

I'm trying to bind a list of objects to a list box. Each object is shown in separate text block. But the problem is that each item should be shown in different format (e.g. Date, currency and so on). I want to store the format in a property of the object ant then set the format in the same binding expression where the value is set. All the examples I've seen so far are showing how to set the string format by hard coding it:

<TextBlock Text="{Binding Value, Mode=OneWay, StringFormat=\{0:n3\}}"/>

I wonder if there is any way to bind the string format property like this:

<TextBlock Text="{Binding Value, Mode=OneWay, StringFormat={Binding myFormat}}"/>

Or maybe it can be achieved by using value converters. But again, is it possible to bind any property to the converter parameter like this:

<TextBlock Text={Binding Value, Converter={StaticResource myConverter}, ConverterParameter={Binding myFormat}}"/>

+1  A: 

Use a value converter that takes the whole object and have this converter access the Value and the Format properties of the object to generate the desired string.

Example:-

 public class ValueFormatConverter : IValueConverter
 {
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        IValueFormat vf = value as IValueFormat;
        if (vf != null)
            return String.Format("{0:" + vf.Format + "}", vf.Value);
        else
            throw new NotSupportedException("value does not implement IValueFormat");
    }
 }

Have the objects in the list implement IValueFormat :-

public interface IValueFormat
{
    object Value { get; }
    string Format { get; }
}

Alternatively

Since your object knows both its value and the format to use to present the value why not simply add a readonly FormattedValue property of type string to the object as well?

If you are implementing INotifyPropertyChanged just make sure you fire PropertyChanged for "FormattedValue" whenever the value or the format has changed.

AnthonyWJones
thank you. I'm gonna try your suggestion
incognito