gpt4 book ai didi

C# WPF 将英文数字转换为阿拉伯数字

转载 作者:行者123 更新时间:2023-11-30 22:48:28 24 4
gpt4 key购买 nike

我需要为我正在处理的应用程序显示阿拉伯数字字符的英文 double 。

这是一个包含 double 的示例类:

public class Class1
{
private double someDouble = 0.874;

public double SomeDouble
{
get { return someDouble; }
}
}

我想在运行时将 SomeDouble 的值转换为以阿拉伯数字字符显示的百分比。这是我一直用作测试的一些快速 XAML:

<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ArabicNumbers"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
x:Class="ArabicNumbers.Window1"
Title="Window1"
Height="300"
Width="300">
<Window.Resources>
<local:Class1 x:Key="Class1Instance" />
<local:DoubleValueConverter x:Key="doubleValueConverter" />
</Window.Resources>

<Grid DataContext="{Binding Source={StaticResource Class1Instance}}">
<TextBlock
HorizontalAlignment="Left"
VerticalAlignment="Top"
TextWrapping="Wrap"
Margin="10"
Text="{Binding SomeDouble, Converter={StaticResource doubleValueConverter}, Mode=Default}"/>
</Grid>

还有我的测试值转换器,DoubleValueConverter:

public class DoubleValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
double valueAsDouble = (double)value;
return valueAsDouble.ToString("P1", culture);
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}

在窗口后面的代码中,我将语言属性设置为当前文化,即“ar-SA”。这似乎是一项要求,因为这会更改 DoubleValueConverter 中 culture 参数的值。

public partial class Window1 : Window
{
public Window1()
{
Language = XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.Name);
InitializeComponent();
}
}

此转换器提供了正确的格式属性,即小数点分隔符,但我需要将这些数字输出为阿拉伯字符而不是“87,4%”。

有没有人对执行此操作的简单方法有任何建议?

最佳答案

我找到了一个非常快速和简单的解决方案。我发现使用阿拉伯字符表示数字是根据语境的;即数字形状取决于同一输出中的前一个文本。

例子:在 TextBlock 元素中输入“1234”作为文本只会以英文形式显示。但是,如果 1234 前面有一些阿拉伯文字(比方说“abcde”),例如 شلاؤيث1234。在此示例中,字符“1234”的前四位数字将采用阿拉伯数字。 (注意:这似乎不适用于该网站 - 在文本框中正确显示,但预览显示数字的英文形状)

有关更多信息,请参阅以下链接:

http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.digitsubstitution.aspx http://msdn.microsoft.com/en-us/library/system.globalization.digitshapes.aspx

从第二个链接来看,我想要的明显选择是 NativeNational,但是由于我们的 CurrentCulture 是由操作系统自动设置的,因此 CurrentCulture 实例是只读的。

为了绕过这个,我只是创建了一个新的 CultureInfo 对象并将 DigitSubstitution 更改为 DigitShapes.NativeNational:

        CultureInfo ci = CultureInfo.CreateSpecificCulture(Thread.CurrentThread.CurrentCulture.Name);
ci.NumberFormat.DigitSubstitution = DigitShapes.NativeNational;
Thread.CurrentThread.CurrentCulture = ci;

关于C# WPF 将英文数字转换为阿拉伯数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1643740/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com