I have WPF application with DataGrid that contain some prices. I want to dynamically change currency and column format must also be adjusted.
The only way i found is to set format by this way:
<DataGridTextColumn Header="Price" Width="95" Binding="{Binding Path=Price, StringFormat=C, ConverterCulture='en-US'}" />
But this binding is static. When I try to bind ConverterCulture to value from code, it throws binding error.
<DataGridTextColumn Header="Price" Width="95" Binding="{Binding Path=Price, StringFormat=C, ConverterCulture="{Binding Source=CurrencyCulture}" />
Is there any way to dynamically change ConverterCulture in Datagrid column format?
Finally I found a solution. Not ideal but seems to work. CurrentContext is my static class to store variables. SelectedCurrency.CurrencyCode is 3-char currency code like USD or EUR. When I change currency in Combobox, string format in column also changes with needed currency symbol.
CultureConverter.cs
public class CultureConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values[0] == null) return string.Empty;
return String.Format(CurrentContext.CultureInfo, "{0:C}", values[0]);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Form.xaml
<Window.Resources>
<providers:CultureConverter x:Key="CultureConverter" />
</Window.Resources>
DataGrid Name="Datagrid" ItemsSource="{Binding Items, Mode=TwoWay}" AutoGenerateColumns="False">
<DataGrid.Columns>
...
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock>
<TextBlock.Text>
<MultiBinding Converter="{StaticResource CultureConverter}">
<Binding Path="InitialCost" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
...
</DataGrid.Columns>
</DataGrid>
private void CB_Currency_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
CurrentContext.CultureInfo =
CultureInfo.GetCultures(CultureTypes.SpecificCultures)
.Where(x => new RegionInfo(x.LCID)
.ISOCurrencySymbol == SelectedCurrency.CurrencyCode)
.First();
}