【问题标题】:OnPropertyChanged not working with nullable decimal type wpfOnPropertyChanged 不适用于可为空的十进制类型 wpf
【发布时间】:2017-01-04 15:40:58
【问题描述】:

我有一个文本框,它绑定到视图模型中的一个属性。我还使用转换器将十进制值转换为货币值。例如,如果我输入 255,则文本值应显示为 $255。但它似乎不起作用。

<TextBox  Margin="479,69,0,0"
                  Height="24"
                  Text="{bindingDecorators:CurrencyBinding FleetAggregate, Mode=TwoWay, Converter={StaticResource DecimalToCurrencyConverter}}" />

虚拟机属性

public decimal? FleetAggregate
        {
            get { return FleetRatesRow.HasStandardAggregate ? (decimal?)FleetRatesRow.fleet_pa_aggregate : (decimal?)null; }
            set
            {
               if  (!value.HasValue)
                {
                    FleetRatesRow.Setfleet_pa_aggregateNull();
                    OnPropertyChanged();
                    return;
                }
                FleetRatesRow.fleet_pa_aggregate = value.Value;
                OnPropertyChanged();
            }            
        }

转换器

 public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            try
            {
                var currencyFormatArg = parameter == null ? new CurrencyFormatArg() : (CurrencyFormatArg)parameter;

                if (value == null)
                {
                    return currencyFormatArg.AllowNull ? string.Empty : DependencyProperty.UnsetValue;
                }

                var currencyValue = (decimal)value;

                string format = currencyValue < 0
                                    ? '-' + currencyFormatArg.Format
                                    : currencyFormatArg.Format;

                string codePrefix = currencyFormatArg.ShowCode ? currencyFormatArg.CurrencyCode + " " : string.Empty;
                return 
                    codePrefix +
                    string.Format(format, currencyFormatArg.CurrencySymbol, Math.Abs(currencyValue));
            }
            catch (Exception)
            {
                return DependencyProperty.UnsetValue;
            }
        }

【问题讨论】:

    标签: c# wpf data-binding


    【解决方案1】:

    您可以使用StringFormat 而不是转换器。也不清楚bindingDecorators:CurrencyBinding 是什么。该属性本身也隐藏了很多复杂性。这不是mcve

    无论如何decimal? 应该像魅力一样工作:

    XAML

    <TextBox Text="{Binding Path=FleetAggregate, StringFormat=${0:0.00}}"/>
    

    代码背后

    public class DummyViewModel
    {
        private decimal? _fleetAggregate;
        public decimal? FleetAggregate
        {
            get
            {
                return _fleetAggregate;
            }
            set
            {
                _fleetAggregate = value;
                //OnPropertyChanged();
            }
        }
    
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-12
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      • 2016-12-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多