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}}"/>
Use a value converter that takes the whole object and have this converter access the
Valueand theFormatproperties of the object to generate the desired string.Example:-
Have the objects in the list implement
IValueFormat:-Alternatively
Since your object knows both its value and the format to use to present the value why not simply add a readonly
FormattedValueproperty of typestringto the object as well?If you are implementing
INotifyPropertyChangedjust make sure you firePropertyChangedfor “FormattedValue” whenever the value or the format has changed.