在纯XAML中,是否可以动态选择字符串格式?

时间:2015-06-09 22:01:42

标签: c# wpf xaml .net-4.5

我必须显示代表价格的小数。

如果价格是英镑或日元,则需要将其显示为4位小数,否则需要将其显示为6位小数。

货币编码为字符串,将为GBpYEN或其他(例如EUR)。货币字符串和价格都在ViewModel中。我正在使用MVVM。

我想知道是否可以使用纯XAML选择正确的字符串格式?

1 个答案:

答案 0 :(得分:2)

使用几个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>

对于上面的示例,我创建了一个名为Currency的类,其中string属性为Name。 VM名为ObservableCollection<Currency>,名为CurrenciesCurrency名为SelectedCurrencydecimal名称为Price。{/ p>