Xamarin.Forms Edit decimal as percent

343 views Asked by At

I have a decimal value I want to display and edit as a percentage using Xamarin.Forms <Entry /> control. I have tried to use IValueConverter but when I'm editing the cursor is all over the place and its really difficult to edit properly and simply. I get the same using StringFormat=.

a) How can I just edit the decimal as * 100 simply and easily?

b) Can I show a % symbol?

c) Can I do the conversion conditionally: when field Y = 1, show as percentage, When field Y = 2, show as decimal?

1

There are 1 answers

0
Wendy Zang - MSFT On

a) How can I just edit the decimal as * 100 simply and easily? b) Can I show a % symbol?

You could use UnFocused event to show the decimal value as % symbol.

Xaml:

 <Entry x:Name="entry" Unfocused="entry_Unfocused"/>

Code:

  private void entry_Unfocused(object sender, FocusEventArgs e)
    {
        var entry = sender as Entry;
        decimal value;
        if (Decimal.TryParse(entry.Text, out value))
        {
            entry.Text = value.ToString("P");
        }
        else
        {
            DisplayAlert("Error", "Please input decimal", "Cancel");
        }

    }

enter image description here

c) Can I do the conversion conditionally: when field Y = 1, show as percentage, When field Y = 2, show as decimal?

Xaml:

 <StackLayout>
        <Label x:Name="label" Text="Y:" />
        <Entry x:Name="entry_Y" />
        <Entry x:Name="entry" Unfocused="entry_Unfocused" />

    </StackLayout>

Code:

 private void entry_Unfocused(object sender, FocusEventArgs e)
    {
        var entry = sender as Entry;
        if (entry_Y.Text=="1")
        {               
            decimal value;
            if (Decimal.TryParse(entry.Text, out value))
            {
                entry.Text = value.ToString("P");
            }
            else
            {
                DisplayAlert("Error", "Please input decimal", "Cancel");
            }
        }
        else if (entry_Y.Text == "2")
        {
            decimal value;
            if (Decimal.TryParse(entry.Text, out value))
            {
                entry.Text = value.ToString();
            }
            else
            {
                DisplayAlert("Error", "Please input decimal", "Cancel");
            }
        }

    }

enter image description here