Tony
Tony

Reputation: 17657

Why this UWP Binding to decimal property is not working properly?

I have a decimal property called TG

public class Dados_Pessoa : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public decimal TG { get; set; }
    // ...
}

public class Pessoa : INotifyPropertyChanged
{
    public Pessoa Propriedades { get; set; }
    // ...
}

I put on the XAML:

<TextBox Header="TG" HorizontalAlignment="Left"  Margin="145,416,0,0" VerticalAlignment="Top" Width="224"
         Text="{Binding Path=Pessoa.Propriedades.TG, Mode=TwoWay}"
/>

When I change the TextBox value and move to other field, this error appears in Visual Studio 2017 output:

Error: Cannot save value from target back to source. BindingExpression: Path='Pessoa.Propriedades.TG' DataItem='Entidades.Formularios.FormFichaCadastro'; target element is 'Windows.UI.Xaml.Controls.TextBox' (Name='null'); target property is 'Text' (type 'String').

If I change the decimal to double it works fine, as expected.

I want to use decimal to have more precision in the numbers.

Why is this behaviour and how to fix this?

Upvotes: 3

Views: 1182

Answers (1)

Tony
Tony

Reputation: 17657

I solved it by creating a Converter for these fields that I Bind to Decimal data type.

public class DecimalConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {            
        Decimal.TryParse((string)value, out decimal result);
        return result;
    }
}

Then I declared it

<Page.Resources>
    <local:DecimalConverter x:Key="DecimalConverter" />
</Page.Resources>

and used :

<TextBox Header="TG" HorizontalAlignment="Left"  Margin="145,416,0,0" VerticalAlignment="Top" Width="224"
         Text="{Binding Path=Pessoa.Propriedades.TG, Mode=TwoWay, Converter={StaticResource DecimalConverter}}"
         />

Upvotes: 4

Related Questions