我必须显示代表价格的小数。
如果价格是英镑或日元,则需要将其显示为4位小数,否则需要将其显示为6位小数。
货币编码为字符串,将为GBp
或YEN
或其他(例如EUR
)。货币字符串和价格都在ViewModel中。我正在使用MVVM。
我想知道是否可以使用纯XAML选择正确的字符串格式?
答案 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>
,名为Currencies
,Currency
名为SelectedCurrency
,decimal
名称为Price
。{/ p>