问题
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').
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>
The entity class:
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;
}
}
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?
回答1:
I got it to work by changing Binding ComponentDec
to x:Bind ComponentDec
I think this is because x:Bind
allows targetType
to be passed as System.Decimal
. Whereas Binding
passes the targetType
as System.Object
.
To use Binding
I will need to write a DecimalConverter
as @schumi1331 suggested.
来源:https://stackoverflow.com/questions/40926596/cannot-save-decimal-property-from-uwp-textbox