windows NumberBox在WinUI 3中不显示实际值

qvtsj1bj  于 11个月前  发布在  Windows
关注(0)|答案(2)|浏览(139)

我的WinUI 3应用程序中的一个数字框将浮点值5.94显示为“5.939999995”。此数字框绑定到视图模型的浮点属性。还有其他数字框绑定到同一视图模型的不同示例,其他数字框可以正常显示其浮点值(精细的意思是显示2个十进制数字,由绑定到所有这些数字框的数字格式化程序定义)。
数字框Xaml定义:

<NumberBox
  Value="{x:Bind Path=MainVM.ViewModel[5].SomeNumber, Mode=TwoWay}"
  />

字符串
如前所述,每个数字框都附加了一个数字格式化程序,将十进制数字限制为2位,但这仍然不能解释为什么5.94没有显示为5.94。

7z5jn7bk

7z5jn7bk1#

Binary floating point math is like this的一个。
但在这种情况下,您可以实现一个自定义的number formatter,例如:

public class DoubleFormatter : INumberFormatter2, INumberParser
{
    public virtual string Format { get; set; } = "{0:F2}"; // by default we use this but you can change it in the XAML declaration
    public virtual string FormatDouble(double value) => string.Format(Format, value);
    public virtual double? ParseDouble(string text) => double.TryParse(text, out var dbl) ? dbl : null;

    // we only support doubles
    public string FormatInt(long value) => throw new NotSupportedException();
    public string FormatUInt(ulong value) => throw new NotSupportedException();
    public long? ParseInt(string text) => throw new NotSupportedException();
    public ulong? ParseUInt(string text) => throw new NotSupportedException();
}

字符串
注意:它没有记录AFAIK,但INumberFormatter2必须也实现INumberParser,否则你会得到更多外来的神秘错误的“无效参数”...
示例XAML:

<StackPanel>
    <StackPanel.Resources>
        <local:DoubleFormatter x:Key="df" /> <!-- change Format here -->
    </StackPanel.Resources>
    <NumberBox NumberFormatter="{StaticResource df}" Value="{x:Bind MyFloatValue, Mode=TwoWay}" />
</StackPanel>

vsikbqxv

vsikbqxv2#

IIRC,这是NumberFormatter的问题。你能试试这个代码吗?

namespace NumberBoxExample;

// Customize the return values if you need to.
public class CustomIncrementNumberRounder : INumberRounder
{
    public double RoundDouble(double value) => value;

    public int RoundInt32(int value) => value;

    public long RoundInt64(long value) => value;

    public float RoundSingle(float value) => value;

    public uint RoundUInt32(uint value) => value;

    public ulong RoundUInt64(ulong value) => value;
}

个字符

相关问题