简体   繁体   English

String.Format没有在Xamarin.Forms中提供正确的字符串

[英]String.Format is not giving the correct string in Xamarin.Forms

I want to display text in a format in label, but it's displaying an incorrect value. 我想以标签中的格式显示文本,但是显示的值不正确。

It's showing the correct value in debug mode. 它在调试模式下显示正确的值。 But its displayed wrong on the screen. 但是它在屏幕上显示错误。 Ideally, the screen should display total and subtotal as image one. 理想情况下,屏幕应将总计和小计显示为图像一。

调试模式下的字符串值

在此处输入图片说明

Code to format string 代码以格式化字符串

string paymentFormat = "{0,-25} {1,8}\n";
string paymentMode = "Total"; // Or Subtotal
string paymentAmount = "604.00";

string test = string.Format(paymentFormat, paymentMode, paymentAmount);

Update 更新资料

public class AlertPopupViewItem : ContentView
{
    Label HeaderLabel,MessageLabel;
    public Button OKButton, CancelButton;
    AbsoluteLayout _overlay;
    LoggerService logservice;
    public bool ButtonValue = false;
    StackLayout CancelStackLayout, OKStackLayout;
    string PageSource = string.Empty;

    public AlertPopupViewItem()
    {
        logservice = new LoggerService();
        logservice.WriteData(Constants.DEBUG_LOGGING, "Alert Message Popup ctor.. Start");

        _overlay = new AbsoluteLayout
        {
            BackgroundColor = Color.Black.MultiplyAlpha(0.5),
            HorizontalOptions = LayoutOptions.Fill,
            VerticalOptions = LayoutOptions.Fill,
        };

        Grid mainGrid = new Grid
        {
            HeightRequest = 40,
            BackgroundColor = Color.White,
            Padding = 20,
            RowDefinitions =
            {

                new RowDefinition { Height = new GridLength(15, GridUnitType.Star) },//0 Title
                new RowDefinition { Height = new GridLength(3, GridUnitType.Star) },//1 Line
                new RowDefinition { Height = new GridLength(80, GridUnitType.Star) },//2 Message
                new RowDefinition { Height = new GridLength(12, GridUnitType.Star) },//3 OK-Cancel
            }
        };

        HeaderLabel = new Label
        {
            FontAttributes = FontAttributes.Bold,
            FontSize = 22,
            TextColor = Color.Black,
            HorizontalTextAlignment= TextAlignment.Center,
            VerticalTextAlignment = TextAlignment.Center,
            HorizontalOptions = LayoutOptions.CenterAndExpand,
            VerticalOptions =LayoutOptions.CenterAndExpand
        };


        BoxView divider = new BoxView
        {
            HeightRequest = 1,
            Color = Color.Gray,
            VerticalOptions = LayoutOptions.End,
        };



        MessageLabel = new Label
        {
            FontAttributes = FontAttributes.None,
            FontSize = 13,
            HorizontalTextAlignment = TextAlignment.Start,
            VerticalTextAlignment = TextAlignment.Center,
            HorizontalOptions = LayoutOptions.StartAndExpand,
            TextColor = Color.Black
        };

        ScrollView scroll = new ScrollView()
        {
            Orientation = ScrollOrientation.Vertical
        };

        scroll.Content = MessageLabel;

        Grid ButtonGrid = new Grid
        {

            HeightRequest = 35,
            ColumnDefinitions =
            {
                new ColumnDefinition {Width=new GridLength(58,GridUnitType.Star) },
                new ColumnDefinition {Width=new GridLength(20,GridUnitType.Star) },
                new ColumnDefinition {Width=new GridLength(2,GridUnitType.Star) },
                new ColumnDefinition {Width=new GridLength(20,GridUnitType.Star) }
            }
        };


        CancelStackLayout = new StackLayout
        {
            Padding = new Thickness(-6, -6, -6, -6),
            //VerticalOptions = LayoutOptions.Center,
            BackgroundColor = Color.FromHex("#ff9500")
        };

        CancelButton = new Button
        {
            TextColor = Color.White,
            FontSize = 15,
            BorderRadius = 0,
            Text = Localizer.Localize("CancelSmall"),
            BackgroundColor = Color.FromHex("#01458e"),
            HorizontalOptions =LayoutOptions.FillAndExpand,
            VerticalOptions=LayoutOptions.FillAndExpand,
            BorderColor = Color.Transparent
        };


        CancelButton.Clicked += CancelButtonClicked;

        CancelStackLayout.Children.Add(CancelButton);
        ButtonGrid.Children.Add(CancelStackLayout, 1, 0);

        OKStackLayout = new StackLayout
        {
            Padding = new Thickness(-6, -6, -6, -6),
            BackgroundColor = Color.FromHex("#ff9500")
        };


        OKButton = new Button
        {
            TextColor = Color.White,
            FontSize = 15,
            BorderRadius = 0,
            Text = Localizer.Localize("OK"),
            BackgroundColor = Color.FromHex("#01458e"),
            HorizontalOptions = LayoutOptions.FillAndExpand,
            VerticalOptions = LayoutOptions.FillAndExpand,
            BorderColor = Color.Transparent
        };
        OKButton.Clicked += OKButtonClicked;

        OKStackLayout.Children.Add(OKButton);
        ButtonGrid.Children.Add(OKStackLayout, 3, 0);


        mainGrid.Children.Add(HeaderLabel, 0, 0);

        mainGrid.Children.Add(divider, 0, 1);

        mainGrid.Children.Add(scroll, 0, 2);

        mainGrid.Children.Add(ButtonGrid, 0, 3);



        AbsoluteLayout.SetLayoutFlags(mainGrid, AbsoluteLayoutFlags.All);

        AbsoluteLayout.SetLayoutBounds(mainGrid, Findlayoutbounds(new Rectangle(0.20, 0.25, 0.5, 0.50)));


        _overlay.Children.Add(mainGrid);


        Content = _overlay;
        logservice.WriteData(Constants.DEBUG_LOGGING, "Alert Message Popup ctor.. End");
    }

   // ThreadHandle thread = new ThreadHandle();
    private void CancelButtonClicked(object sender, EventArgs e)
    {
        ButtonValue = false;
        this.IsVisible = false;
       // thread.WorkMethod();
    }

    private void OKButtonClicked(object sender, EventArgs e)
    {

        ButtonValue = true;
        if (PageSource == "StarterPage") ;
        //MessagingCenter.Send(this, "ModifyValBooleanForAlert");
        this.IsVisible = false;

       // thread.WorkMethod();
    }

    Rectangle Findlayoutbounds(Rectangle fractionalRect)
    {
        if (fractionalRect.Width - 1 == 0)
            fractionalRect.Width = 0.99;
        if (fractionalRect.Height - 1 == 0)
            fractionalRect.Height = 0.99;
        Rectangle layoutbounds = new Rectangle
        {
            X = fractionalRect.X / (1 - fractionalRect.Width),
            Y = fractionalRect.Y / (1 - fractionalRect.Height),
            Width = fractionalRect.Width,
            Height = fractionalRect.Height
        };

        return layoutbounds;
    }

    public void DisplayAlertPopup(string alertBoxTitle, string alertBoxContent,bool CancelDisplay)
    {
        HeaderLabel.IsVisible = false;
        CancelStackLayout.IsVisible = CancelDisplay;
        CancelButton.IsVisible = CancelDisplay;
        HeaderLabel.Text = alertBoxTitle;
        MessageLabel.Text = alertBoxContent;
        OKButton.Text = Localizer.Localize("OK");
        CancelButton.Text = Localizer.Localize("CancelSmall");
        HeaderLabel.IsVisible = true;
    }

    public void DisplayAlertPopup(string alertBoxTitle, string alertBoxContent, string ButtonText)
    {
        CancelStackLayout.IsVisible = false;
        CancelButton.IsVisible = false;
        HeaderLabel.Text = alertBoxTitle;
        MessageLabel.Text = alertBoxContent;
        OKButton.Text = ButtonText;
    }

    public void DisplayAlertConditionalPopup(string alertBoxTitle, string alertBoxContent, bool CancelDisplay)
    {
        CancelStackLayout.IsVisible = CancelDisplay;
        CancelButton.IsVisible = CancelDisplay;
        HeaderLabel.Text = alertBoxTitle;
        MessageLabel.Text = alertBoxContent;
        this.IsVisible = true;

    }

    public void SetButtonText(string OKText, string CancelText)
    {
        if (OKText != null)
            OKButton.Text = OKText;
        if (CancelText != null)
            CancelButton.Text = CancelText;
    }

}

I get the formatted string from some other class and call the DisplayAlertPopup method. 我从其他一些类获取格式化的字符串,然后调用DisplayAlertPopup方法。 MessageLabel is the label for which I am setting this value. MessageLabel是我为其设置此值的标签。

Update2: 更新2:

As suggested in answer, I have tried the below code to set the font for Android. 如答案中所建议,我尝试了以下代码来设置Android的字体。 But its also not displying the text in the required format. 但是它也不会以所需的格式显示文本。

MessageLabel = new Label
    {
        FontAttributes = FontAttributes.None,
        FontSize = 13,
        HorizontalTextAlignment = TextAlignment.Start,
        VerticalTextAlignment = TextAlignment.Center,
        HorizontalOptions = LayoutOptions.StartAndExpand,
        TextColor = Color.Black,
        FontFamily = "Droid Sans Mono"
    };

You will need to use a fixed-width font. 您将需要使用固定宽度的字体。 There is unfortunately none that is built-in across all platforms, but each platform has its own: 不幸的是,所有平台都没有内置任何组件,但是每个平台都有其自己的:

  • iOS - Courier New iOS-Courier新
  • Android - Droid Sans Mono Android-Droid Sans Mono
  • UWP - Consolas UWP-Consolas

If no built-in font suits you or you want to have the same experience on all platforms, you can also use custom fonts in Xamarin.Forms. 如果没有适合您的内置字体,或者您希望在所有平台上都具有相同的体验,则还可以在Xamarin.Forms中使用自定义字体。 This requires you to find a fixed-width font you like on a service like Google Fonts . 这要求您在Google字体之类的服务上找到所需的固定宽度字体 Then you can follow the tutorial here on Xamarin Help , that describes how to include the TTF file in each platform and use it from XAML. 然后,您可以按照Xamarin帮助上的教程进行操作,该教程描述了如何在每个平台中包含TTF文件以及如何从XAML使用它。

The short summary is: 简短的摘要是:

  1. Add the font to each platform project with appropriate build action (UWP - Content, iOS - Bundle Resource, Android - Android Asset) 使用适当的构建操作将字体添加到每个平台项目(UWP-内容,iOS-捆绑资源,Android-Android资产)
  2. Use the OnPlatform syntax to set the font (ideally creating a static resource so that it can be reused): 使用OnPlatform语法来设置字体(理想情况下是创建静态资源,以便可以重复使用):

Resource: 资源:

<OnPlatform x:TypeArguments="x:String" x:Key="MyFontFamily">
    <On Platform="Android" Value="MyFont.ttf#Open Sans" />
    <On Platform="UWP" Value="/Assets/MyFont.ttf#Open Sans" />
    <On Platform="iOS" Value="MyFont" />
</OnPlatform>

And use like this: 像这样使用:

<Label FontFamily="{StaticResource MyFontFamily}" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM