如何在 UWP 中为 NumberBox 应用 PercentFormatter?

2023-12-06

我想在最后添加百分比(0%-100%)。它正确显示 %,但它在末尾添加更多零,如下所示,

enter image description here

        double number = 75;
        NumberBoxnumberBox = new NumberBox {  };
        PercentFormatter percentFormatter = new PercentFormatter();
        percentFormatter.FractionDigits = 0;
        percentFormatter.IntegerDigits = 1;
        numberBox.NumberFormatter = percentFormatter;
        numberBox.Value=number;

这实际上是预料之中的。 PercentFormatter 接受任意数字并使用以下(数学)规则对其进行格式化:1=100%。所以就你而言,75 is 7500%。要实现在数字后附加“%”的效果,您可以编写自己的格式化程序并使用它:

public class AppendPercentageSignFormatter : INumberFormatter2, INumberParser
{
    public string FormatInt(long value)
    {
        return value.ToString() + "%";
    }

    public string FormatUInt(ulong value)
    {
        return value.ToString() + "%";
    }

    public string FormatDouble(double value)
    {
        return value.ToString() + "%";
    }

    public long? ParseInt(string text)
    {
        // Cut off the percentage sign at the end of the string and parse that.
        return long.Parse(text.Substring(0, text.Length - 1));
    }

    public ulong? ParseUInt(string text)
    {
        // Cut off the percentage sign at the end of the string and parse that.
        return ulong.Parse(text.Substring(0, text.Length - 1));
    }

    public double? ParseDouble(string text)
    {
        // Cut off the percentage sign at the end of the string and parse that.
        return double.Parse(text.Substring(0, text.Length - 1));
    }
}

// And later in your UI:
double number = 75;
numberBox.NumberFormatter = new AppendPercentageSignFormatter();
numberBox.Value = number;

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 UWP 中为 NumberBox 应用 PercentFormatter? 的相关文章

随机推荐