【问题标题】:Entry value converter hangs converting and converting back again and again入口值转换器一次又一次地挂起转换和转换回来
【发布时间】:2016-08-19 10:06:23
【问题描述】:

我有一个 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;
    }
}

问题:我的问题是,当我运行项目并尝试在价格字段中输入值时,代码在 ConvertConvertBack 转换器和应用程序的功能挂起!
有什么建议吗?

【问题讨论】:

  • 我不久前也遇到过这个问题,虽然这是一个数字舍入问题。通常,您需要以某种方式打破链条。我看到在 ConvertBack 您没有将字符串转换为小数。你能检查一下是否有帮助吗?当if (this.price == value) 行被点击时,数字是多少,它们在任何时候评估为真吗?
  • 是的@joe 那是错误,我已经找到了......这有点复杂,因为我们有一些渲染器,在那些渲染器中我们再次设置了值,所以它变成了一个无限循环...

标签: binding xamarin.forms ivalueconverter valueconverter


【解决方案1】:

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

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 块可帮助您停止 getset 之间的循环。 我希望它可以帮助某人。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-31
    • 2020-05-20
    • 2023-03-15
    • 2013-04-15
    • 2011-02-15
    • 1970-01-01
    • 1970-01-01
    • 2017-12-25
    相关资源
    最近更新 更多