System.FormatException in MVVMCross

最后都变了- 提交于 2019-12-25 09:54:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!