Xamarin 形成导致无限循环的值转换器 [英] Xamarin forms value converter causing infinite loop

查看:20
本文介绍了Xamarin 形成导致无限循环的值转换器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用转换器获得一个简单的双向绑定示例,但是一旦条目中的值发生变化,例如,如果您输入 1,它就会陷入无限循环,它会到达 ConvertBack 的末尾方法并正确设置值.然后它再次点击 ConvertBack 方法,除了这次使用值 11,下一次它将是 111 并且一直运行直到它使模拟器崩溃.

I am trying to get a simple two way binding example working with a converter but as soon as the value in the entry changes for example if you enter 1 it gets stuck in an infinite loop, it gets to the end of the ConvertBack method and sets the value correctly. It then hits the ConvertBack method again except this time with the value 11, the next time it will be 111 and just keeps going until it crashes the emulator.

即使我停止调试,模拟器也会无限地将数字输入到新的搜索窗口中.

Even when I stop debugging, the emulator just keeps entering the number into a new search window infinitely.

转换器:

public class StringToNullableInt : IValueConverter
{
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo language)
    {
        if (string.IsNullOrEmpty(value?.ToString()))
        {
            return null;
        }
        else
        {
            int tmp = 0;
            if (Int32.TryParse(value.ToString(), out tmp))
            {
                return tmp;
            }
            else
            {
                return null;
            }
        }
    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo language)
    {
        return value;
        //throw new NotImplementedException();
    }
}

要绑定的字段

public int? Test
    {
        get
        {
            return _test;
        }
        set
        {
            if (value != _test)
            {
                _test = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("Test"));
            }
        }
    }

界域

<Entry Text="{Binding Test, Mode=TwoWay, Converter={StaticResource cnvStringToNullableInt} }" />

推荐答案

将 Int 绑定到 Entry 不是一个好的解决方案(对我来说).

Bind a Int to an Entry is not a good solution (for me).

我建议有一个 TestString 属性

I suggest to have a TestString property

string _testString {get;set;}
public string TestString {
    get{
       return _testString;

    }
    set{
        try {
            _testString = value;
            _test = int.Parse(_testString);
        }
        catch {    _test = null;}
    }
}

现在你可以尝试用TestString绑定,不用IValueConverter

now you can try to bind with TestString, without IValueConverter

这篇关于Xamarin 形成导致无限循环的值转换器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆