无法从 UWP 文本框保存小数属性 [英] Cannot Save Decimal Property from UWP TextBox
问题描述
我在 UWP 中有 2 个文本框.它们绑定到模型实体上的整数和小数属性.整数属性被保存,但小数返回错误
I have 2 TextBoxes in UWP. They are bound to integer and decimal properties on the model entity. The integer property is saved but the decimal returns the error
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 是:
The relevant XAML is:
<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 中借用:
The converter was shamelessly borrowed from 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);
}
为什么小数属性不保存?
Why doesn't the decimal property save?
推荐答案
我通过将 Binding ComponentDec
更改为 x:Bind ComponentDec
我认为这是因为 x:Bind
允许将 targetType
作为 System.Decimal
传递.而 Binding
将 targetType
作为 System.Object
传递.
I think this is because x:Bind
allows targetType
to be passed as System.Decimal
. Whereas Binding
passes the targetType
as System.Object
.
要使用 Binding
,我需要按照 @schumi1331 的建议编写一个 DecimalConverter
.
To use Binding
I will need to write a DecimalConverter
as @schumi1331 suggested.
这篇关于无法从 UWP 文本框保存小数属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!