如果我有一个名为MyObject的对象,它有一个名为MyChild的属性,而这个属性本身又有一个名为Name的属性。如果我只有一个绑定路径(例如"MyChild.Name"),以及对MyObject的引用,如何获取该Name属性的值?
MyObject
-MyChild
-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));
}
}
Resolver
的类,该类具有一个 Resolve
方法,其行为类似于 @ThomasLevesque 的 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]"
我是这样做的。如果这是一个可怕的想法,请告诉我,因为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
不确定你想做什么以及如何(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>