2016-04-25 32 views
0

我有一个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转换器和应用程序的功能挂起!
有什么建议吗?

+2

前段时间我也遇到过这个问题,虽然这是一个数字舍入问题。一般来说,你需要以某种方式打破连锁。我看到在ConvertBack中,你并没有将字符串转换为小数。你可以检查看看是否有帮助吗?当'if(this.price == value)'行被击中时,这些数字是什么,他们在任何时候都评估为真? – joe

+0

是@joe那是错误,我已经找到它了......这有点复杂,因为我们有一些渲染器,而在那些渲染器中,我们再次设置了值,所以它变成了一个infinit循环...... –

回答

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(); 
    } 
} 

如果块可帮助您阻止之间循环得到设置。 我希望它可以帮助别人。