c# - 为什么这个 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');目标属性是“文本”(类型“字符串”)。
如果我将其更改decimal
为double
它可以正常工作,正如预期的那样。
我想用decimal
更精确的数字。
为什么会出现这种行为以及如何解决这个问题?
解决方案
我通过为绑定到十进制数据类型的这些字段创建转换器来解决它。
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}}"
/>
推荐阅读
- python - 如何使用 mongoimport 将 csv 合并到集合中
- angular - Angular HttpInterceptor 不适用于登录后的第一个请求
- android - 为什么用jsoup解析后img标签没有src值?
- latex - \afterpage 和 \endfloat
- javascript - 如何绕过请求限制?
- javascript - how can i fix my javascript calculation which is not working?
- python - 如何将我自己的模块导入到一个scrapy项目中?
- css - 如何将 INSPINIA 引导程序添加到 Ember 应用程序
- php - .htaccess HTTPS 重定向工作,但 HTTPS 去 /index.php
- java - 我的外键没有被插入到数据库中,知道我做错了什么吗?