开发者

AssociatedObject.FindName in Silverlight behavior OnAttached method returns null

开发者 https://www.devze.com 2022-12-18 18:19 出处:网络
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.

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: A开发者_C百科ssociatedObject.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?


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;
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号