输入值转换器会一次又一次地挂起转换和转换

时间:2016-04-25 20:23:07

标签: binding xamarin.forms ivalueconverter valueconverter

我有一个Entry,其中包含价格,我想将其格式化为货币。
这是Entry代码

<Entry x:Name="Price" StyleId="Price"  
       Text="{Binding Model.Price, Converter={StaticResource CurrencyEntryFormatConverter}, Mode=TwoWay}"
       Placeholder="{x:Static resx:Resources.PricePlaceholder}"
       Style="{StaticResource DefaultEntry}" Keyboard="Numeric"/>

这是Model

中的属性
public decimal Price
{
    get
    {
        return this.price;
    }

    set
    {
        if (this.price== value)
        {
            return;
        }

        this.price= value;
        this.OnPropertyChanged();
    }
}

最后这是转换器:

public class CurrencyEntryFormatConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null || string.IsNullOrWhiteSpace(value.ToString()))
        {
            return value;
        }

        string result = string.Format(Resources.CurrencyFormatString, (decimal)value);
        return result;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null || string.IsNullOrWhiteSpace(value.ToString()))
        {
            return 0;
        }

        string result = value.ToString().Replace(" ", "").Replace("$", "").Replace(",", "");
        return result;
    }
}

问题我的问题是,当我运行项目并尝试在价格字段中输入值时,代码会在转换 ConvertBack <之间重复执行/ strong>转换器和应用程序的功能挂起!
有什么建议吗?

1 个答案:

答案 0 :(得分:1)

在我的情况下,问题是财产实施
如果我们定义一个实现INotifyPropertyChanged的类的属性,为了在属性值更改时更新视图,我们需要在OnPropertyChanged块中调用set方法:

public decimal Amount
{
    get
    {
        return this.amount;
    }

    set
    {
        this.amount = value;
        this.OnPropertyChanged();  // like this line
    }
}

但是这样的代码就像你的绑定一样循环。所以我们需要检查值是否与当前属性的值不同,然后如果它是新的,则更新它。看看这段代码:

public decimal Amount
{
    get
    {
        return this.amount;
    }

    set
    {
        if (this.amount == value)
        {
            return;
        }

        this.amount = value;
        this.OnPropertyChanged();
    }
}

if 块可帮助您停止获取设置之间的循环。 我希望它有所帮助。