I am creating a behavior to extend the functionality of the Entry control.
Here is the code for the behavior:
public class EntryExtendedBehavior : Behavior<Entry>
{
public static readonly BindableProperty ValueProperty = BindableProperty.Create<EntryExtendedBehavior, int>(p => p.Value, 0, propertyChanged: OnValueChange, defaultBindingMode: BindingMode.TwoWay);
public static readonly BindableProperty FormatProperty = BindableProperty.Create<EntryExtendedBehavior, string>(p => p.Format, string.Empty, propertyChanged: OnFormatChange);
private static void OnValueChange(BindableObject bindable, int oldvalue, int newvalue)
{
var e = bindable as EntryExtendedBehavior;
if (e == null)
throw new Exception("ExtendedEntry.OnValueChange bindable == null");
e.Value = newvalue;
}
private static void OnFormatChange(BindableObject bindable, string oldvalue, string newvalue)
{
var e = bindable as EntryExtendedBehavior;
if (e == null)
throw new Exception("ExtendedEntry.OnFormatChange bindable == null");
e.Format = newvalue;
}
public int Value
{
get { return (int)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
public string Format
{
get { return (string)GetValue(FormatProperty); }
set { SetValue(FormatProperty, value); }
}
protected override void OnAttachedTo(Entry entry)
{
entry.Focused += OnFocused;
entry.Unfocused += OnUnfocused;
}
protected override void OnDetachingFrom(Entry entry)
{
entry.Focused -= OnFocused;
entry.Unfocused -= OnUnfocused;
}
private void OnFocused(object sender, FocusEventArgs e)
{
Entry entry = sender as Entry;
if (entry == null)
throw new Exception("ExtendedEntry.OnFocus sender == null");
entry.Text = entry.Text.RemoveFormat(Format);
}
private void OnUnfocused(object sender, FocusEventArgs e)
{
Entry entry = sender as Entry;
if (entry == null)
throw new Exception("ExtendedEntry.OnUnfocused sender == null");
var unformattedValue = entry.Text.RemoveFormat(Format);
Value = Convert.ToInt32(unformattedValue);
entry.Text = unformattedValue.ApplyFormat(Format, Value);
}
}
And this is the xaml code that binds to the properties:
<Entry Grid.Column="1" Grid.Row="1" Text="{Binding PurchasePrice, Mode=OneWay, Converter={StaticResource fieldConverter}, ConverterParameter=Dollar}" Keyboard="Numeric" TextColor="{StaticResource textColor}" >
<Entry.Behaviors>
<b:EntryExtendedBehavior Format="Dollar" Value="{Binding PurchasePrice, Mode=TwoWay}" />
</Entry.Behaviors>
</Entry>
The Format property works correctly but the Value property seems to be completely ignored. I'm assuming that it's something stupid that I'm just missing but I can't figure it out.
A little background; the entire reason for this binding it to attempt to make the Entry control only bind to the backing VM property when it looses focus. doing a normal two way binding caused it to call back to the VM on every keystroke. This being a financial app, I don't want to recalculate that often.
Thanks