In pure XAML, is it possible to select a string format on the fly?

506 views Asked by At

I have to display a decimal representing a price.

If the price is in British Pence or Yen, it needs to display it to 4 decimal places, otherwise it needs to display it to 6 decimal places.

The currency is encoded as a string, and will be GBp or YEN or other (e.g. EUR). Both the currency string and the price are in the ViewModel. I am using MVVM.

I am wondering if its possible to select the correct string format using nothing but pure XAML?

1

There are 1 answers

1
goobering On BEST ANSWER

Easy peasy with a couple of DataTriggers:

<Grid x:Name="LayoutRoot">
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>

    <ListBox Grid.Row="0"
                ItemsSource="{Binding Currencies}"
                SelectedItem="{Binding SelectedCurrency,
                                    Mode=TwoWay,
                                    UpdateSourceTrigger=PropertyChanged}"
                DisplayMemberPath="Name" />

    <TextBlock FontSize="30" Grid.Row="1">
        <TextBlock.Style>
            <Style TargetType="TextBlock">
                <Setter Property="Text" Value="{Binding Price, UpdateSourceTrigger=PropertyChanged, StringFormat=C6}" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Path=SelectedCurrency.Name}" Value="GBP">
                        <Setter Property="Text" Value="{Binding Price, UpdateSourceTrigger=PropertyChanged, StringFormat=C4}" />
                    </DataTrigger>
                    <DataTrigger Binding="{Binding Path=SelectedCurrency.Name}" Value="YEN">
                        <Setter Property="Text" Value="{Binding Price, UpdateSourceTrigger=PropertyChanged, StringFormat=C4}" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBlock.Style>
    </TextBlock>
</Grid>

For the above example I've made a class called Currency which has a string property Name. The VM has an ObservableCollection<Currency> called Currencies, an instance of Currency called SelectedCurrency, and a decimal property called Price.