Search code examples
c#.netwpfpopupelementname

Element binding broken in dynamically added child


I have created a Popup control in WPF which dynamically creates a popup and adds it to the first child in the display tree. Within the popup's content (PopupContent), binding works but element binding seems to be broken.

I am blaming this on the way I am creating the popup. Is there a way to fix this so that Element binding within the Popup's content works as expected?

popupContainer = new PopupContainer();
popupContainer.Content =   PopupContent;
PopupContent.Visibility = Visibility.Visible;
rootContent.Children.Add(popupContainer);

Solution

  • PopUp controls have a separate VisualTree and is not part of main Window/UserControl's VisualTree and that's why Elementname binding's won't work.

    A Popup control does not have its own visual tree; it instead returns a size of 0 (zero) when the MeasureOverride method for Popup is called. However, when you set the IsOpen property of Popup to true, a new window with its own visual tree is created. The new window contains the Child content of Popup.

    http://msdn.microsoft.com/en-us/library/ms749018.aspx#PopupandtheVisualTree

    What you can try is a workaround which is genrally used with ContextMenus, i.e. to add the popup in the same namescope as your window/UserControl -

    popupContainer = new PopupContainer();       
    popupContainer.Content =   PopupContent;       
    PopupContent.Visibility = Visibility.Visible;       
    rootContent.Children.Add(popupContainer);  
    NameScope.SetNameScope(popupContainer, NameScope.GetNameScope(this)); //Or
    // NameScope.SetNameScope(popupContainer, NameScope.GetNameScope(rootContent));