AssociatedObject.FindName in Silverlight behavior OnAttached method returns null

StackOverflow https://stackoverflow.com/questions/2145924

  •  23-09-2019
  •  | 
  •  

문제

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?

도움이 되었습니까?

해결책

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;
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top