文本框绑定到对象中断绑定(类型)

时间:2015-06-23 15:11:02

标签: c# wpf data-binding binding

在我的应用程序中,我遇到了一个问题,我用一个小的演示应用程序进行了模拟。

我有一个ListBoxItem的ViewModel,它具有Type object的Value属性。这可以是Int32,Decimal,String ......

当我加载Value而没有编辑它时,它保持不变Type

enter image description here

当我在文本框中附加一个4并获得值

enter image description here

该属性变为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));
            }
        }
    }

2 个答案:

答案 0 :(得分:1)

.NET Framework会将您的int转换为string以显示在TextBox中。我只能想象你的实际属性类型是object,因此框架不知道将它转换回来的类型(例如。intstring。如果您使用强类型属性,例如,它将起作用。类型为int

答案 1 :(得分:1)

您输入文字数据。如果您的数据源实现为int,则TextBox具有应用ValidationError的默认设置,并使用默认转换器作为默认类型。但对于没有CLR元数据的未知类型,当您将TextBox中的/ ConvertBack值转换为属性时,它只是调用.ToString(),反之亦然。 如果需要,您可以编写自己的转换器IValueConverter。