【问题标题】:Textbox binding to object breaks binding (type)文本框绑定到对象中断绑定(类型)
【发布时间】: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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 我认为 BindingExpression 将根据编译类型而不是运行时确定类型。因此,当 Binding 更新源时,它可能会找到一个对象而不是运行时类型 Int32。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-20
    • 1970-01-01
    相关资源
    最近更新 更多