0

いくつかのプロパティを持つオブジェクトがあります。これらのうちの 2 つは、ターゲット テキスト ボックスの幅と高さを制御するために使用されます。ここに簡単な例があります...

<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 は時間の経過とともに更新される可能性があるため、データ テンプレートに固定パスを単純に配置することはできません。

4

1 に答える 1

1

を実装して、これを Text プロパティIMultiValueConverterとして使用できます。BindingConverterしかし、パスが指している値ではなく、プロパティ (パス自体) が変更Textboxされた場合にのみ値が更新されるという問題があります。その場合は、リフレクションを使用してバインディング パスの値を返すObjPatha を使用できます。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>
于 2012-08-16T07:25:10.753 に答える