views:

23

answers:

2

Hi, if I have an object say called MyObject, which has a property called MyChild, which itself has a property called Name. How can I get the value of that Name property if all I have is a binding path (i.e. "MyChild.Name"), and a reference to MyObject?

MyObject
  -MyChild
    -Name
A: 

not sure what you want to do but and how (xaml or code) yet you can always name your object

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

an then use it in code

myBindingObject.Something.Name

or in xaml

<BeginStoryboard>
 <Storyboard>
    <DoubleAnimation
        Storyboard.TargetName="myBindingObject"
        Storyboard.TargetProperty="Background"
        To="AA2343434" Duration="0:0:2" >
    </DoubleAnimation>
 </Storyboard>
</BeginStoryboard>
lukas
+2  A: 

I found a way to do this, but it's quite ugly and probably not very fast... Basically, the idea is to create a binding with the given path and apply it to a property of a dependency object. That way, the binding does all the work of retrieving the value:

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));
    }
}
Thomas Levesque
@Thomas. That seems like a lot of machinery to get the value of a binding but I can't think of a better general purpose code solution. +1 and Cheers.
Berryl
Excellent, thanks Thomas! The reason I need something like this is because I have written a custom markup extension for loading images. This extension has a Name property for the image name, which I now want to bind to a model property in a DataTemplate which uses the markup extension. However, I can't bind because Name isn't a DP, nor can it be :( This was the only solution I could think of, so I will give this code a try. Thanks.
devdigital