【问题标题】:Format number with leading spaces if digit not available如果数字不可用,则使用前导空格格式化数字
【发布时间】:2016-09-12 05:10:04
【问题描述】:

在 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。

【问题讨论】:

    标签: c# wpf xaml xamarin xamarin.forms


    【解决方案1】:

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

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

    更多解释请参见Xamarin.Forms documentation

    【讨论】:

      【解决方案2】:

      你可以使用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
          }
      }
      

      【讨论】:

      • 我知道但是,它会再次将代码添加到 CodeBehind 类中,这是避免的。我一直在寻找一种可以在不更改 CodeBehind 的情况下完全在 XAML 中完成的方法。
      • @Vishnu 是的,目前还没有想到从 XAML 中执行此操作,也许其他人会有想法。
      猜你喜欢
      • 2014-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-03
      • 1970-01-01
      • 1970-01-01
      • 2019-10-14
      • 1970-01-01
      相关资源
      最近更新 更多