I have a MvvmCross app and I am using a Date Value Converter as follows:
public class DateToStringConverter : IMvxValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo language)
{
if ((value != null) && (value.GetType() == typeof(DateTime)))
{
DateTime tmp = (DateTime)value;
return tmp.ToString("MM/dd/yyyy");
}
return "";
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo language)
{
DateTime dt;
if (DateTime.TryParse(value.ToString(), out dt))
return dt;
return null;
}
}
I have it bound to an EditText as follows:
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="date"
android:id="@+id/txtinventorydate"
style="@style/InputEditText"
local:MvxBind="Text ShipmentInventory.InventoryDate, Mode=TwoWay, Converter=DateToStringConverter" />
When it loads the value from the database, it looks fine, but every time I type a character, it fires Convert. It never fires ConvertBack. If you are in the middle of typing a date, it seems it would not want to do this until you are finished because a half typed date is not a valid date. Anyone got any ideas why it might be acting this way? Is there a better way to bind a date field to an EditText? When I leave out the converter, it populates it with the entire date and time and I only want the date. Someone please help.
Jim
To solve this, you could add a binding for FocusText
which would only update on losing focus. There was discussion recently about introducing FocusText
within MvvmCross - based on MvvmCross: change update source trigger property of binding on MonoDroid - but I don't believe that ever made it through to a Pull Request.
However, really, in a mobile UI entering dates by free text is generally frowned upon - better to use a specialized Date control instead - e.g. like https://github.com/MvvmCross/MvvmCross-Tutorials/blob/master/ApiExamples/ApiExamples.Droid/Resources/Layout/Test_Date.axml#L12