#Xamarin Forms Currency Entry Field

images.jpgI needed a simple Entry field in Xamarin Forms which would work as a currency field. It should show 0.00 when empty, but then clear out automatically once the user tapped it. I ended up using a simple behavior to accomplish it in a very simply way.

currency.gif

Here’s how:

Create a file called CurrencyBehavior.cs in your shared project:

public class CurrencyBehavior : Behavior<Entry>
    {
	    private bool _hasFormattedOnce = false;
	    protected override void OnAttachedTo(Entry entry)
	    {
		    entry.TextChanged += OnEntryTextChanged;
			entry.Focused += EntryOnFocused;
			entry.Unfocused += EntryOnUnfocused;
		    base.OnAttachedTo(entry);
	    }
 
	    private void EntryOnUnfocused(object senderFocusEventArgs e)
	    {
		    var entry = sender as Entry;
		    if (entry?.Text.HasValues()==false)
		    {
			    entry.Text = "0.00";
		    } 
	    }
 
	    private void EntryOnFocused(object senderFocusEventArgs e)
	    {
		    var entry =  sender as Entry;
		    if (entry?.Text == "0.00")
		    {
			    entry.Text = "";
		    }
	    }
 
	    protected override void OnDetachingFrom(Entry entry)
	    {
		    entry.TextChanged -= OnEntryTextChanged;
		    entry.Focused -= EntryOnFocused;
		    entry.Unfocused -= EntryOnUnfocused;
		    base.OnDetachingFrom(entry);
	    }
 
	    private   void OnEntryTextChanged(object senderTextChangedEventArgs args)
	    {
		    if (!_hasFormattedOnce && args.NewTextValue == "0")
		    {
			    ((Entrysender).Text = "0.00";
			    _hasFormattedOnce = true;
		    }
	    }
 
 
    }

Now, on your Entry control, add the behavior:

	            <Entry 
	                   Text="{Binding MyMoneyPropertyInMyViewModel}"
	                   Keyboard="Numeric">
		            <Entry.Behaviors>
			            <behaviors:CurrencyBehavior />
		            </Entry.Behaviors>
	            </Entry>

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s