MyObjectというオブジェクトがあり、MyChildというプロパティがあり、それ自体がNameというプロパティを持っているとします。バインディングパス(つまり「MyChild.Name」)とMyObjectへの参照だけがある場合、そのNameプロパティの値を取得するにはどうすればよいですか?
MyObject
-MyChild
-Name
MyObjectというオブジェクトがあり、MyChildというプロパティがあり、それ自体がNameというプロパティを持っているとします。バインディングパス(つまり「MyChild.Name」)とMyObjectへの参照だけがある場合、そのNameプロパティの値を取得するにはどうすればよいですか?
MyObject
-MyChild
-Name
私はこれを行う方法を見つけましたが、それはかなり醜く、おそらくそれほど速くはありません...基本的に、アイデアは、指定されたパスでバインディングを作成し、それを依存関係オブジェクトのプロパティに適用することです。このようにして、バインディングは値を取得するすべての作業を実行します。
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));
}
}
私はあなたが必要としていることを正確に実行するnugetパッケージ Pather.CSharpを開発しました。
これには、 @ThomasLevesqueのメソッドのように動作Resolver
するメソッドを持つクラスが含まれています。例:Resolve
GetValue
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]"
何をしたいのか、どのように(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>
私はそれをこのようにやっています。これがひどい考えであるかどうかを教えてください。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