如果数字不可用,则带有前导空格的格式编号

时间:2016-09-12 05:10:05

标签: c# wpf xaml xamarin xamarin.forms

在Xamarin XAMl / WPF中,我尝试使用StringFormat,但它不起作用。 我需要绑定一个整数值,范围从1位到3位,但需要有前导空格,以便UI在值变化时不会改变。

我尝试在XAML中关注,但它不起作用:

 <Label Text="{Binding JpegQualityValue, StringFormat={}{0,3:###}}" />

以下作品:

 <Label Text="{Binding FormattedJpegQualityValue}" />

后面有额外的代码:

    public string FormattedJpegQualityValue
    {
        get
        {
            return string.Format("{0,3:###}", JpegQualityValue);
        }
    }

有什么方法可以只在XAML中使用,而不需要修改格式后面的代码? 我添加了WPF标记/关键字,因为大多数代码与WPF类似。

2 个答案:

答案 0 :(得分:1)

StringFormat表达式更改为StringFormat='{0,3:###}'

提供给StringFormat的值应该在单引号内,以防止Xaml表达式解析器被{}字符混淆。

有关详细说明,请参阅Xamarin.Forms documentation

答案 1 :(得分:0)

您可以使用PadLeft

JpegQualityValue.ToString().PadLeft(3,'0');

否则,您可以使用

您可以使用转换器,当您需要使用值时,这通常是在WPF中完成的

<Label Text="{Binding FormattedJpegQualityValue, 
              Converter={StaticResource ZeroesConverter}}"}" />

// obviously, following is not in your xaml.
public class ZeroesConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        // put logic here. 
        // convert int to string, look at length, append zeroes, or use the string formatter if you want
        value.ToString().PadLeft(3,'0');
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        // throw some exception. you don't need this
    }
}