1
我在UWP中有2个文本框。它们绑定到模型实体上的整数和小数属性。该整数属性被保存,但小数返回错误无法从UWP文本框中保存十进制属性
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;
}
}
转换器是无耻地从模板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);
}
为什么不保存小数属性?
也许尝试将“decimal”更改为“decimal?”因为类型转换器正在寻找可以为空的东西 – RoguePlanetoid
谢谢@RoguePlanetoid,但尝试过同样的错误。 – Vague
我已经做了一些调试,发现当它试图将值保存回来时'ConvertBack'方法的'Type targetType'是'System.Object'而不是'System.Decimal',但我不知道为什么。怎么写一个DecimalValueConverter? – schumi1331