質問

メソッドの出力にバインドしようとしています。今、私はこれを使用した例を見てきました ObjectDataProvider ただし、これの問題は、ObjectDataProvider がメソッドを呼び出すオブジェクトの新しいインスタンスを作成することです。現在のオブジェクトインスタンスで呼び出されるメソッドが必要な場合。現在、コンバータを動作させるために試しています。

設定:

Class Entity
{
   private Dictionary<String, Object> properties;

   public object getProperty(string property)
  {
      //error checking and what not performed here
     return this.properties[property];
  }
}

XAML への私の試み

     <local:PropertyConverter x:Key="myPropertyConverter"/>
      <TextBlock Name="textBox2">
          <TextBlock.Text>
            <MultiBinding Converter="{StaticResource myPropertyConverter}"
                          ConverterParameter="Image" >
              <Binding Path="RelativeSource.Self" /> <!--this doesnt work-->
            </MultiBinding>
          </TextBlock.Text>
        </TextBlock>

私のコードビハインド

public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
    string param = (string)parameter;
    var methodInfo = values[0].GetType().GetMethod("getProperty", new Type[0]);
    if (methodInfo == null)
        return null;
    return methodInfo.Invoke(values[0], new string[] { param });               
}

public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
    throw new NotSupportedException("PropertyConverter can only be used for one way conversion.");
}

私の問題は、現在のエンティティをコンバータに渡せないことです。したがって、リフレクションを使用して getProperty メソッドを取得しようとすると、操作するものが何もありません

ありがとう、ステフ

役に立ちましたか?

解決

メソッドの呼び出しを get プロパティ内にラップし、この get プロパティを現在の DataContext であるクラスに追加します。

編集:更新された質問に回答します。

valueconverter にパラメータを 1 つだけ渡す場合は、multivalueconverter は必要なく、通常の valueconverter (IValueConverter を実装) を使用するだけです。また、valueconverter 内のオブジェクトを Distionary にキャストし、リフレクションを使用する代わりにそれを直接使用してみてはいかがでしょうか。

現在のデータコンテキストをバインディングとして渡すには、次のようにします。 <Binding . />. 。テキストブロックのデータコンテキストはエンティティだと思います。

ただし、辞書項目にアクセスする前にコードを実行するだけであれば、これはすべて必要ありません。代わりにインデックス プロパティを使用するだけで、それに直接データバインドできます。

public class Entity 
{ 
   private Dictionary<String, Object> properties; 

   public object this[string property]
   {
        get
        { 
            //error checking and what not performed here 
            return properties[property]; 
        }
    } 
} 

<TextBlock Text="{Binding Path=[Image]}" />
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top