views:

336

answers:

1

I'm making a Silverlight behavior to enable dragging an element by a contained "drag handle" element (rather than the whole element being draggable). Think of it like a window title bar.

In the OnAttached method I am calling: AssociatedObject.FindName(DragHandle) but this is returning null.

I then tried handling the AssociatedObject's Loaded event and running my code there, but I still get a null returned.

Am I misunderstanding what FindName is able to do? The AssociatedObject is in an ItemsControl (I want a collection of draggable elements). So is there some kind of namescope problem?

+1  A: 

Yes, it sounds like a namescope problem. The MSDN documentation on XAML namescopes goes over how namesopes are defined for templates and item controls. Are you using a template for the items in your ItemsControl?

You may just have to walk the visual tree recursively with something like this to find the correct element by name:

    private static FrameworkElement FindChildByName(FrameworkElement parent, string name)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
        {
            FrameworkElement child = VisualTreeHelper.GetChild(parent, i) as FrameworkElement;

            if (child != null && child.Name == name)
            {
                return child;
            }
            else
            {
                FrameworkElement grandChild = FindChildByName(child, name);

                if (grandChild != null)
                {
                    return grandChild;
                }
            }
        }

        return null;
    }
Dan Auclair