【问题标题】:WPF - binding complex objects to simple controlsWPF - 将复杂对象绑定到简单控件
【发布时间】:2014-08-13 11:09:24
【问题描述】:

我创建了一个名为“BoundProperty”的类,其中包含一个属性“Value”。

绑定到作为该类实例的属性看起来是这样的 (年龄是一个BoundProperty):

<TextBox Text="{Binding MyModel.Age.Value, Mode=TwoWay}" />

有没有办法让绑定看起来像这样,另外仍然保留双向?

<TextBox Text="{Binding MyModel.Age, Mode=TwoWay}" />

我不能使用隐式/显式转换运算符,因为这个“BoundProperty”初始化需要特殊参数,需要从原始对象复制。

谢谢, 广告

【问题讨论】:

  • 您在哪里/如何使用该 BoundProperty?

标签: wpf data-binding binding


【解决方案1】:

如果 Value 是公开的,您可以使用 ValueConverter:

public class BoundPropertyConverter:IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var age = value as BoundProperty;
        if (age == null)
            return string.Empty;
        return age.Value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        int age;
        if (int.TryParse(value.ToString(), out age))
            return new BoundProperty() {Value = age};
        return null;
    }
}

然后在 xaml 中为这个转换器定义命名空间

xmlns:converters="clr-namespace:Your.Namespace"

然后在资源区写下这样的内容:

<converters:BoundPropertyConverter x:Key="BoundPropertyConverter"/>

最后但同样重要的是:

<TextBox Text="{Binding MyModel.Age, Mode=TwoWay, Converter={StaticResource BoundPropertyConverter}" />

【讨论】:

  • 这很好,但我想隐式使用这个转换器,而不是在我的 xaml 代码中提及它。有没有办法做到这一点,例如通过实现一些接口?
  • 不幸的是,我没有看到任何其他方法可以做到这一点。这是我发布的此类问题的最佳解决方案。我想是的……
猜你喜欢
  • 1970-01-01
  • 2013-07-31
  • 1970-01-01
  • 1970-01-01
  • 2014-12-02
  • 1970-01-01
  • 1970-01-01
  • 2011-08-31
  • 2021-10-06
相关资源
最近更新 更多