无法从UWP TextBox保存十进制属性

时间:2016-12-02 07:04:28

标签: xaml uwp uwp-xaml

我在UWP中有2个TextBox。它们绑定到模型实体上的整数和小数属性。保存整数属性,但十进制返回错误

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').

相关的XAML是:

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

实体类:

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

转换器无耻地借用了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);
    }

为什么小数属性不保存?

1 个答案:

答案 0 :(得分:1)

我通过将Binding ComponentDec更改为x:Bind ComponentDec

来实现目标

我认为这是因为x:Bind允许targetType作为System.Decimal传递。而BindingtargetType作为System.Object传递。

要使用Binding,我需要写一个DecimalConverter作为@ schumi1331建议。