在我的应用程序中,我遇到了一个问题,我用一个小的演示应用程序进行了模拟。
我有一个ListBoxItem的ViewModel,它具有Type object
的Value属性。这可以是Int32,Decimal,String ......
当我加载Value而没有编辑它时,它保持不变Type
当我在文本框中附加一个4并获得值
时
该属性变为String
。
为什么我的TextBox
绑定会在编辑值时更改绑定对象的类型?
修改 这是财产:
public int TestProperty
{
get { return _testProperty; }
set
{
if (Equals(value, _testProperty)) return;
_testProperty = value;
OnPropertyChanged();
}
}
我将Int32值123
分配给它:
TestProperty = 123;
在输入文本框之前和之后,我称之为:
StatusMessage = string.Format("Current Type: {0} Value: {1}", _testProperty.GetType().Name, _testProperty);
编辑2:
它适用于此(将x:Shared
设置为false):
public class PreserveTypeValueConverter : IValueConverter
{
public Type Type { get; private set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
try
{
Type = value.GetType();
return System.Convert.ChangeType(value, targetType, culture);
}
catch (Exception)
{
return new ValidationResult(false, string.Format("Cannot convert {0} to {1}", value.GetType().Name, targetType.Name));
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
try
{
return System.Convert.ChangeType(value, Type, culture);
}
catch (Exception)
{
return new ValidationResult(false, string.Format("Cannot convert {0} to {1}", value.GetType().Name, targetType.Name));
}
}
}
答案 0 :(得分:1)
.NET Framework会将您的int
转换为string
以显示在TextBox
中。我只能想象你的实际属性类型是object
,因此框架不知道将它转换回来的类型(例如。int
) string
。如果您使用强类型属性,例如,它将起作用。类型为int
。
答案 1 :(得分:1)
您输入文字数据。如果您的数据源实现为int,则TextBox具有应用ValidationError的默认设置,并使用默认转换器作为默认类型。但对于没有CLR元数据的未知类型,当您将TextBox中的/ ConvertBack值转换为属性时,它只是调用.ToString(),反之亦然。 如果需要,您可以编写自己的转换器IValueConverter。