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

标签 c# wpf xaml .net-4.5

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

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

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

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

最佳答案

使用几个 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属性(property)Name 。 VM 有一个ObservableCollection<Currency>CurrenciesCurrency 的一个实例叫SelectedCurrency ,以及 decimal属性名为 Price .

关于c# - 在纯 XAML 中,是否可以动态选择字符串格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30743613/

相关文章:

C# - 从 USB 设备属性详细信息中获取最后已知的父设备

c# - 在 UWP 中的 Rtf 和 Html 之间转换

c# - WPF ListView : Attaching a double-click (on an item) event

c# - 如何在运行时将对象转换为可为空的 double?

WPF 将控件可见性绑定(bind)到另一个控件的焦点属性

c# WPF TextBox 按索引检索行时出现错误?

c# - 如何在不使用 HttpContext 的情况下获取 Web 应用程序的当前配置?

WPF 轮播/旋转元素

wpf - 从类库关闭 WPF 应用程序 (Caliburn.Micro)

xaml - 网格中一行的用户控件