views:

965

answers:

3

I have a ComboBox bound to an ObservableCollection of decimals. What is the correct way to apply our currency converter to the items?

Edit:

a) I have an existing currency converter that I must use b) .NET 3.0

Do I need to template the items?

A: 

Use StringFormat in the Binding expression like

<TextBox Text="{Binding Path=Value, StringFormat=Amount: {0:C}}"/>

See this blog for more details.

A ValueConverter is another way - StringFormat doesnt work on .NET3.0 it needs WPF3.5 SP1.

Jobi Joy
+1  A: 

You can use the ItemStringFormat property on ComboBox to tell it how to format each of its items:

<ComboBox ItemStringFormat="c">

However, be aware that when using "c" as a currency formatter, it will use the currency defined by the local machine. If your values are defined in $ but your client PC is running with pounds or yen as their currency symbol, they won't be seeing what you want them to see.

Matt Hamilton
We have a specific currency converter that we use and I do need to use that one. Thanks though.
Donnelle
Yeah if you have code you need to call then an IValueConverter implementation is the best way.
Matt Hamilton
But do I do that through an item template, and what is the correct way of setting the selected value?
Donnelle
+3  A: 

Your best bet if you have some code to do the conversion is indeed to run each item through an IValueConverter via a template.

<Window.Resources>
    <my:CurrencyConverter x:Key="currencyConverter" />

    <DataTemplate x:Key="thingTemplate" DataType="{x:Type my:Thing}">
        <TextBlock
            Text="{Binding Amount,Converter={StaticResource currencyConverter}}" />
    </DataTemplate>
</Window.Resources>

<ComboBox
    ItemSource="... some list of Thing instances ..."
    ItemTemplate="{StaticResource thingTemplate}" />

So you just define your CurrencyConverter class such that it implements IValueConverter and calls your code to turn the given amount into a formatted string.

Matt Hamilton