从对象恢复路径的WPF数据绑定?

从对象恢复路径的WPF数据绑定?,wpf,data-binding,Wpf,Data Binding,我有一个具有多个属性的对象。其中两个用于控制目标文本框的宽度和高度。这里有一个简单的例子 <DataTemplate DataType="{x:Type proj:SourceObject}"> <TextBox Width="{Binding ObjWidth}" Height="{Binding ObjHeight}"/> </DataTemplate> 我还想绑定TextBox的Text属性。要绑定的实际属性不是固定的,而是在SourceO

我有一个具有多个属性的对象。其中两个用于控制目标文本框的宽度和高度。这里有一个简单的例子

<DataTemplate DataType="{x:Type proj:SourceObject}">
    <TextBox Width="{Binding ObjWidth}" Height="{Binding ObjHeight}"/>
</DataTemplate>

我还想绑定TextBox的Text属性。要绑定的实际属性不是固定的,而是在SourceObject的字段中命名的。所以理想情况下我会想这样做

<DataTemplate DataType="{x:Type proj:SourceObject}">
    <TextBox Width="{Binding ObjWidth}" Height="{Binding ObjHeight}"
             Text="{Binding Path={Binding ObjPath}"/>
</DataTemplate>

这里的ObjPath是一个字符串,它返回一个对绑定完全有效的路径。但这不起作用,因为无法对binding.Path使用绑定。你知道我怎样才能做到同样的事情吗


关于更多内容,我将指出SourceObject是用户可自定义的,因此ObjPath可以随时间更新,因此我不能简单地在数据模板中放置固定路径。

您可以实现一个
IMultiValueConverter
,并将其用作文本属性的
BindingConverter
。但是问题是,
Textbox
的值只有在
ObjPath
属性更改(路径本身)时才会更新,而不是路径所指向的值。如果没有问题,您可以使用
BindingConverter
,它使用反射返回绑定路径的值

class BindingPathToValue : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value[0] is string && value[1] != null)
        {
            // value[0] is the path
                    // value[1] is SourceObject
            // you can use reflection to get the value and return it
            return value[1].GetType().GetProperty(value.ToString()).GetValue(value[1], null).ToString();
        }
        return null;
    }

    public object[] ConvertBack(object value, Type[], object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
将转换器放在您的资源中:

<proj:BindingPathToValue x:Key="BindingPathToValue" />

并在XAML中使用它:

<DataTemplate DataType="{x:Type proj:SourceObject}">
    <TextBox Width="{Binding ObjWidth}" Height="{Binding ObjHeight}">
        <TextBox.Text>
            <MultiBinding Mode="OneWay" Converter="{StaticResource BindingPathToValue}">
                <Binding Mode="OneWay" Path="ObjPath" />
                <Binding Mode="OneWay" Path="." />
            </MultiBinding>
        </TextBox.Text>
    </TextBox>
</DataTemplate>

能否将ObjPath的值移动到资源?然后可以编写Text=“{Binding Path={DynamicResource ObjPath}”