Lalit_vicky
Lalit_vicky

Reputation: 295

OnPropertyChanged not working with nullable decimal type wpf

I have a Textbox and thats bound to a property in viewmodel. Also I am using a converter to convert the decimal value to currency value. eg, if I enter 255 the text value should display $255. But it doesn't seems to be working.

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

VM Property

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

Converter

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

Upvotes: 0

Views: 414

Answers (1)

Mat
Mat

Reputation: 2072

You could use StringFormat instead of using a converter. It's also not clear what bindingDecorators:CurrencyBinding is. The property itself also hides a lot of complexity. This is by far no mcve.

Anyway decimal? should work like a charm:

XAML

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

Code Behind

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


}

Upvotes: 1

Related Questions