15

MyObjectというオブジェクトがあり、MyChildというプロパティがあり、それ自体がNameというプロパティを持っているとします。バインディングパス(つまり「MyChild.Name」)とMyObjectへの参照だけがある場合、そのNameプロパティの値を取得するにはどうすればよいですか?

MyObject
  -MyChild
    -Name
4

4 に答える 4

26

私はこれを行う方法を見つけましたが、それはかなり醜く、おそらくそれほど速くはありません...基本的に、アイデアは、指定されたパスでバインディングを作成し、それを依存関係オブジェクトのプロパティに適用することです。このようにして、バインディングは値を取得するすべての作業を実行します。

public static class PropertyPathHelper
{
    public static object GetValue(object obj, string propertyPath)
    {
        Binding binding = new Binding(propertyPath);
        binding.Mode = BindingMode.OneTime;
        binding.Source = obj;
        BindingOperations.SetBinding(_dummy, Dummy.ValueProperty, binding);
        return _dummy.GetValue(Dummy.ValueProperty);
    }

    private static readonly Dummy _dummy = new Dummy();

    private class Dummy : DependencyObject
    {
        public static readonly DependencyProperty ValueProperty =
            DependencyProperty.Register("Value", typeof(object), typeof(Dummy), new UIPropertyMetadata(null));
    }
}
于 2010-08-26T20:35:28.823 に答える
4

私はあなたが必要としていることを正確に実行するnugetパッケージ Pather.CSharpを開発しました。

これには、 @ThomasLevesqueのメソッドのように動作Resolverするメソッドを持つクラスが含まれています。例:ResolveGetValue

IResolver resolver = new Resolver(); 
var o = new { Property1 = Property2 = "value" } }; 
var path = "Property1.Property2";    
object result = r.Resolve(o, path); //the result is the string "value"

インデックスを介したコレクションアクセスやキーを介した辞書アクセスもサポートしています。
これらのパスの例は次のとおりです。

"ArrayProperty[5]"
"DictionaryProperty[Key]"
于 2015-12-30T22:09:52.067 に答える
0

何をしたいのか、どのように(xamlまたはコード)するのかはわかりませんが、いつでもオブジェクトに名前を付けることができます

<MyObject x:Name="myBindingObject" ... />

その後、コードで使用します

myBindingObject.Something.Name

またはxamlで

<BeginStoryboard>
 <Storyboard>
    <DoubleAnimation
        Storyboard.TargetName="myBindingObject"
        Storyboard.TargetProperty="Background"
        To="AA2343434" Duration="0:0:2" >
    </DoubleAnimation>
 </Storyboard>
</BeginStoryboard>
于 2010-08-26T17:45:21.953 に答える
0

私はそれをこのようにやっています。これがひどい考えであるかどうかを教えてください。C#は私にとって単なる副業であり、私は専門家ではありません。objectToAddToはItemsControlタイプです。

BindingExpression itemsSourceExpression = GetaBindingExression(objectToAddTo);
object itemsSourceObject = (object)itemsSourceExpression.ResolvedSource;
string itemSourceProperty = itemsSourceExpression.ResolvedSourcePropertyName;

object propertyValue = itemsSourceObject.GetType().GetProperty(itemSourceProperty).GetGetMethod().Invoke(itemsSourceObject, null); // Get the value of the property
于 2018-02-05T13:14:54.847 に答える