问题
The following code updates properties on-the-fly via mvvmcross messaging protocol.
The problem that I am facing now, when user clears either age or category textviews, then I am getting systemformat exception, I guess when textview gets blank, it does not parse it to a number?
System.FormatException: Input string was not in a correct format.
MainViewModel
private readonly IMvxMessenger _messenger;
private readonly MvxSubscriptionToken _token;
public MainViewModel(IMvxMessenger messenger) {
_messenger = messenger;
_token = messenger.Subscribe<SelectedItemMessage>(OnMessageReceived);;
}
private void OnMessageReceived(SelectedItemMessage obj)
{
Age = obj.Age;
Category= obj.Category;
}
DetailViewModel
private readonly IMvxMessenger _messenger;
public DetailViewModel(IMvxMessenger messenger) {
_messenger = messenger;
}
public void UpdateMethod() {
var message = new SelectedItemMessage(this, age, category);
_messenger.Publish(message, typeof(SelectedItemMessage));
}
SelectedItemMessage
public SelectedItemMessage(object sender, double age, int category) : base(sender)
{
Age = age;
Category = category;
}
public double Age { get; set; }
public int Category{ get; set; }
}
回答1:
You need a value converter which converts empty string to null and you need to make Age property nullable. After that you will need to specify the converted in the binding:
public class NullableValueConverter : MvxValueConverter
{
public override object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value;
}
public override object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null || string.IsNullOrEmpty(value.ToString()))
{
return null;
}
return value;
}
}
and inside your view:
local:MvxBind="Text Age,Converter=Nullable;"
You can read more about value converters at Value Converters Wiki
来源:https://stackoverflow.com/questions/36753822/system-formatexception-in-mvvmcross