我在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);
}
为什么小数属性不保存?
答案 0 :(得分:1)
我通过将Binding ComponentDec
更改为x:Bind ComponentDec
我认为这是因为x:Bind
允许targetType
作为System.Decimal
传递。而Binding
将targetType
作为System.Object
传递。
要使用Binding
,我需要写一个DecimalConverter
作为@ schumi1331建议。