![](/img/trans.png)
[英]WPF DataGridComboboxColumn not getting property (value from Database) binding to enum
[英]WPF - Getting a property value from a binding path
如果我有一個名為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 ,它可以完全滿足您的需求。
它包含一個類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]"
不知道你想做什么但是如何(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#對我來說只是一個副作用所以我不是專家對象ToAddTo屬於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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.