我无法在XAML中为标签设置带前导空格的双值格式。
前导空格对我来说是必要的,因为我希望标签显示一定数量的字符用于对齐:
<Viewbox Grid.Column="1" >
<Label xml:space="preserve" Content="{Binding PwVal, FallbackValue='Power'}" ContentStringFormat='#####.0' Foreground="White" HorizontalContentAlignment="Right" VerticalContentAlignment="Center" Margin="0" FontFamily="Consolas">
</Label>
</Viewbox>
ContentStringFormat='#####.0'
不工作。然而,'0000.0'
给出前导零,但我想要的是前导空格。
使用复合格式:
<Label ... ContentStringFormat="{}{0,7:0.0} />
与其使用Label,不如使用更简单的TextBlock元素而不是Label,并将其Text属性与适当的StringFormat:绑定
<TextBlock Text="{Binding PwVal, StringFormat={}{0,7:0.0}}" ... />
我倾向于使用TextBlock。
然而。也许你真的需要一个标签,无论出于什么原因。
当您将标签的内容绑定到某个内容时,通常的行为是控件在其内容中放置一个文本块。正是这一点显示了绑定的数据。
标签是一种内容控件。
这种行为的一个奇怪之处在于,它使用ContentStringFormat来格式化进入该文本块的数据。
因此,你也可以做一些类似的事情:
<Label Content="{Binding PwVal}"
ContentStringFormat="{}{0,6:0.0}"
/>
请注意ContentStringFormat。
我添加了一些标记来向自己证明,我在绑定值之前得到了两个空格。
<Label Content="{Binding PwVal}"
BorderBrush="Black"
BorderThickness="2"
HorizontalAlignment="Left"
VerticalAlignment="Top"
ContentStringFormat="{}{0,6:0.0}"
/>