WPF-将复杂对象绑定到简单控件
我创建了一个名为“BoundProperty”的类,其中包含一个属性“Value” 绑定到作为该类实例的属性的方式如下 (年龄是一个有边界的属性):WPF-将复杂对象绑定到简单控件,wpf,data-binding,binding,Wpf,Data Binding,Binding,我创建了一个名为“BoundProperty”的类,其中包含一个属性“Value” 绑定到作为该类实例的属性的方式如下 (年龄是一个有边界的属性): 有没有一种方法可以使绑定看起来像这样,并且仍然保持双向 <TextBox Text="{Binding MyModel.Age, Mode=TwoWay}" /> 我不能使用隐式/显式转换运算符,因为此“BoundProperty”初始化需要特殊参数,需要从原始对象复制这些参数 谢谢, AD如果值为公共值,则可以使用Value
有没有一种方法可以使绑定看起来像这样,并且仍然保持双向
<TextBox Text="{Binding MyModel.Age, Mode=TwoWay}" />
我不能使用隐式/显式转换运算符,因为此“BoundProperty”初始化需要特殊参数,需要从原始对象复制这些参数
谢谢,
AD如果值为公共值,则可以使用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}" />
在何处/如何使用BoundProperty?这很好,但我希望隐式使用此转换器,而不是在我的xaml代码中提及它。有没有一种方法可以做到这一点,例如通过实现一些接口?不幸的是,我没有看到任何其他方法可以做到这一点。我发布的这篇文章是解决这类问题的最佳方法。我认为是这样。。。
<TextBox Text="{Binding MyModel.Age, Mode=TwoWay, Converter={StaticResource BoundPropertyConverter}" />