Vague
Vague

Reputation: 2280

Cannot Save Decimal Property from UWP TextBox

I have 2 TextBoxes in UWP. They are bound to integer and decimal properties on the model entity. The integer property is saved but the decimal returns the error

Cannot save value from target back to source. BindingExpression: Path='ComponentDec' DataItem='Orders.Component'; target element is 'Windows.UI.Xaml.Controls.TextBox' (Name='null'); target property is 'Text' (type 'String').

The relevant XAML is:

                    <ListView
                        Name="ComponentsList"
                        ItemsSource="{Binding Components}">
                        <ListView.ItemTemplate>
                            <DataTemplate>
                                <StackPanel Orientation="Horizontal">
                                    <TextBox Text="{Binding ComponentInt,Mode=TwoWay}"></TextBox>
                                    <TextBox Text="{Binding ComponentDec,Mode=TwoWay,Converter={StaticResource ChangeTypeConverter}}"></TextBox>
                                </StackPanel>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>

The entity class:

public class Component
{
    public string ComponentCode { get; set; }
    public string ComponentDescription { get; set; }
    public int ComponentInt { get; set; }
    public decimal ComponentDec { get; set; }
    public override string ToString()
    {
        return this.ComponentCode;
    }
}

The converter was shamelessly borrowed from Template 10:

public class ChangeTypeConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        if (targetType.IsConstructedGenericType && targetType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
        {
            if (value == null)
            {
                return null;
            }
            targetType = Nullable.GetUnderlyingType(targetType);
        }

        if (value == null && targetType.GetTypeInfo().IsValueType)
            return Activator.CreateInstance(targetType);

        if (targetType.IsInstanceOfType(value))
            return value;

        return System.Convert.ChangeType(value, targetType);
    }

Why doesn't the decimal property save?

Upvotes: 1

Views: 858

Answers (1)

Vague
Vague

Reputation: 2280

I got it to work by changing Binding ComponentDec to x:Bind ComponentDec

I think this is because x:Bind allows targetType to be passed as System.Decimal. Whereas Binding passes the targetType as System.Object.

To use Binding I will need to write a DecimalConverter as @schumi1331 suggested.

Upvotes: 1

Related Questions