Reputation: 535
It seems when using a Entry
control in Xamarin forms if its not touched then it returns Null
. However, if the user enters anything then clears the control, it returns string.Empty
Ideally I want to just keep the Null
value as these go into the Database and as you can imagine its not very consistent with Null
s and empty strings.
What is the best way to achieve the goal of keeping the Null
regardless if the control has been edited ?
I've considered Converters but this means adding them to all Entry
controls, maybe doing something in the Data Access Layer... not sure what as wouldn't this mean extra code for all the properties.
Upvotes: 0
Views: 1195
Reputation: 535
I actually ended up making a very simple custom control as since I required this function for all Entry controls it made no sense adding Behaviors to each one.
public class EntryEx : Entry
{
protected override void OnTextChanged(string oldValue, string newValue)
{
base.OnTextChanged(oldValue, newValue == string.Empty ? null : newValue);
}
}
Thanks to Jason for the idea.
Upvotes: 0
Reputation: 838
You can use behavior.
Code
public class EntryNullBehavior : Behavior<Entry>
{
protected override void OnAttachedTo(Entry entry)
{
entry.TextChanged += OnEntryTextChanged;
base.OnAttachedTo(entry);
}
protected override void OnDetachingFrom(Entry entry)
{
entry.TextChanged -= OnEntryTextChanged;
base.OnDetachingFrom(entry);
}
void OnEntryTextChanged(object sender, TextChangedEventArgs args)
{
if (sender is Entry entry)
{
if (args.NewTextValue != null && args.NewTextValue.Equals(string.Empty))
{
entry.Text = null;
}
}
}
}
Usgae in Xaml
xmlns:behavior="clr-namespace:DummyTestApp.Behavior"
...
<Entry x:Name="MyNullEntry" HeightRequest="50" FontSize="Large">
<Entry.Behaviors>
<behavior:EntryNullBehavior/>
</Entry.Behaviors>
</Entry>
P.S. Now I don't know what you consider overkill (seeing your comment) but this solution is elegant
Upvotes: 2