如何在 UWP 中为 NumberBox 应用 PercentFormatter?

How to Apply PercentFormatter for a NumberBox in UWP?

我想在末尾添加百分比(0%-100%)。它正确显示 %,但它在末尾添加了更多的零,

        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% 的(数学)规则。所以在你的例子中,757500%。要实现向数字附加“%”的效果,您可以编写自己的格式化程序并使用它:

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;