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