首页 > 解决方案 > 为什么这个 UWP 绑定到十进制属性不能正常工作?

问题描述

我有一个名为 TG 的小数属性

public class Dados_Pessoa : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

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

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

我把 XAML:

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

当我更改 TextBox 值并移至其他字段时,此错误出现在 Visual Studio 2017 输出中:

错误:无法将值从目标保存回源。BindingExpression:路径='Pessoa.Propriedades.TG' DataItem='Entidades.Formularios.FormFichaCadastro';目标元素是'Windows.UI.Xaml.Controls.TextBox'(名称='null');目标属性是“文本”(类型“字符串”)。

如果我将其更改decimaldouble它可以正常工作,正如预期的那样。

我想用decimal更精确的数字。

为什么会出现这种行为以及如何解决这个问题?

标签: c#uwp

解决方案


我通过为绑定到十进制数据类型的这些字段创建转换器来解决它。

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

然后我宣布了

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

并使用:

<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}}"
         />

推荐阅读