title: Popup from code behind in WPF not working ( On resize and switching windows)
body: <p><strong>I want to add a popup on click of a Button in WPF. I dont want to add Popup code in my XAML. It has to be code behind.</strong></p>
  
  <p>My XAML is as follows::</p>
  
  <pre><code>&lt;Window x:Class="Test.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="300"&gt;
     &lt;Grid&gt;
       &lt;Button x:Name="button1" Click="button1_Click"&gt;Button&lt;/Button&gt;
     &lt;/Grid&gt;
  &lt;/Window&gt;
  </code></pre>
  
  <p>My XAML file has a simple button. On click of Button, I am trying to execute the following code.</p>
  
  <pre><code>  private void button1_Click(object sender, RoutedEventArgs e)
      {
          Button button = sender as Button;
  
          Popup codePopup = new Popup();
          TextBlock popupText = new TextBlock();
          popupText.Text = "Popup Text";
          popupText.Background = Brushes.LightBlue;
          popupText.Foreground = Brushes.Blue;
          codePopup.Child = popupText;
  
          codePopup.PlacementTarget = button;
          codePopup.IsOpen = true;
  
      }
  </code></pre>
  
  <p>But why is the popup not <strong>attaching itself to the window</strong>. I mean the popup is displayed even if I switch windows. Also when I <strong>resize window</strong>, Popup is no longer placed near button??</p>