title: Getting PlacementTarget of a ToolTip in code behind
body: <p>As <a href="https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.tooltip.placementtarget" rel="nofollow noreferrer">this MSDN page suggests</a> you should be able to use data binding to set a placement target on a tooltip.</p>
  
  <p>In my UWP app I have the following XAML and code behind:</p>
  
  <pre><code>&lt;Button x:Name="MyButton"&gt;
      &lt;ToolTipService.ToolTip&gt;
          &lt;ToolTip PlacementTarget="{Binding ElementName=MyButton}"
                   Loaded="FunkyMethod"&gt;
              &lt;Border Width="150"
                      Height="50"
                      CornerRadius="10"
                      Background="DeepSkyBlue"&gt;
                  &lt;TextBlock Text="This is a tooltip"
                             HorizontalAlignment="Center"
                             VerticalAlignment="Center"
                             Foreground="White"/&gt;
              &lt;/Border&gt;
          &lt;/ToolTip&gt;
      &lt;/ToolTipService.ToolTip&gt;
  
      &lt;Button.Content&gt;Button with ToolTip&lt;/Button.Content&gt;
  &lt;/Button&gt;
  </code></pre>
  
  <pre class="lang-cs prettyprint-override"><code>private void FunkyMethod(object sender, RoutedEventArgs e)
  {
      var tooltip = sender as ToolTip;
      var button = tooltip?.PlacementTarget as Button; // always returns NULL for the placement target
  
      if (tooltip != null &amp;&amp; button != null)
      {
          // do something funcky here.
      }
  }
  </code></pre>
  
  <p>But the placement target never gets set and I always get NULL. Does anyone know why?</p>
  
  <p>For context, I am trying to write code that would compute the horizontal/vertical offset needed to place a tooltip to the right of its parent and vertically centered. Something like this:</p>
  
  <p><a href="https://i.stack.imgur.com/6a3Gg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6a3Gg.png" alt="enter image description here"></a></p>
  
  <p>But I haven't been able to find a way of achieving this (Placement=Right or Top didn't work). So What I'm trying to do is to do it in code behind at runtime, by a) set Placement=Mouse, b) figure out the parent control via PlacementTarget, c) find out the mouse position relative to the parent control, d) compute the horizontal/vertical offset and set it for the tooltip</p>