【问题标题】:In pure XAML, is it possible to select a string format on the fly?在纯 XAML 中,是否可以动态选择字符串格式?
【发布时间】:2015-06-09 22:01:42
【问题描述】:

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

如果价格是英便士或日元,需要显示到小数点后4位,否则显示到小数点后6位。

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

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

【问题讨论】:

  • 你对使用转换器不感兴趣吧?
  • 为什么不在 ViewModel 中做呢?这是迄今为止最简单的方法。
  • 老实说,它的业务逻辑,可能应该位于 ViewModel 中。我感兴趣的是 XAML 是否具有足够的表现力来独立完成这项工作。

标签: c# wpf xaml .net-4.5


【解决方案1】:

使用几个 DataTrigger 轻松实现:

<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 有一个名为CurrenciesObservableCollection&lt;Currency&gt;、一个名为SelectedCurrencyCurrency 实例和一个名为decimaldecimal 属性。

【讨论】:

  • 太棒了,绝对太棒了!我不认为 XAML 的表现力足以做到这一点。
猜你喜欢
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-27
  • 1970-01-01
相关资源
最近更新 更多