views:

355

answers:

1

I'm working with the Adorner model with drag and drop, and I'm instantiating a DataTemplate through a ContentPresenter and adding it to the Adorner layer of my control/window. The problem I have is I need to register mouse events on the root visual element of the instantiated DataTemplate so I can change state and detect the drop in my Behavior. Since I'm writing a Behavior, I need to access this in code. I can try to attach the events to the presenter itself, but that doesn't do anything, I'm assuming I might be able to use TemplateBinding's in the DataTemplate, but I don't really want to put that burden on the person creating the DataTemplate.

<DataTemplate>
    <TextBlock Text={Binding Path=Name} />
</DataTemplate>

ContentPresenter presenter = new ContentPresenter();
presenter.Child = myDataTemplate;

adornerLayer.Items.Add(presenter);
A: 

Can't you use VisualTreeHelper to walk up the visual tree of the AdornedElement, or try casting framework elements to work through the logical tree?

This method, added to a custom adorner, would retrieve the root visual from the adorned element's tree - probably the Window.

    public UIElement GetRootVisual()
    {
        UIElement root = AdornedElement;
        if (root != null)
        {
            UIElement parent = VisualTreeHelper.GetParent(root) as UIElement;
            if (parent != null)
            {
                root = parent;
            }
        }

        return root;
    }
Jeff Wilcox