无法从 UWP 文本框保存小数 属性

Cannot Save Decimal Property from UWP TextBox

我在 UWP 中有 2 个文本框。它们绑定到模型实体上的整数和小数属性。保存整数 属性 但小数 returns 错误

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>

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

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

为什么小数 属性 不保存?

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

来让它工作

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

要使用 Binding,我需要按照 @schumi1331 的建议写一个 DecimalConverter