【发布时间】:2015-06-23 15:11:01
【问题描述】:
在我的应用程序中,我用一个小演示应用程序模拟了一个问题。
我有一个 ListBoxItem 的 ViewModel,它的 Value 属性类型为 object。这可以是 Int32、Decimal、String ...
当我加载值并在没有编辑的情况下获取它时,它保持不变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));
}
}
}
【问题讨论】:
-
你能显示测试代码,特别是 xaml 吗?
标签: c# wpf data-binding binding