#877 – Placing a Popup Relative to Another Control

By default, a Popup control is placed relative to the XAML element in which it is defined.  If you want its position on the screen to be relative to another element, you can define the Popup within that element or you can use the PlacementTarget property to specify which element should be used when determining the popup’s placement.

In the example below, the default placement will still be along the bottom edge of an element, but the PlacementTarget property is used to locate the Popup below a Button rather than below the StackPanel in which it is defined.

    <StackPanel Margin="15" Orientation="Horizontal" Background="AliceBlue">
        <Button Name="btnLearn"
                Content="Learn About Caesar"
                Margin="5" Padding="10,5"
                VerticalAlignment="Center"
                MouseEnter="Button_MouseEnter">
        </Button>
        <Popup Name="popCaesar" StaysOpen="False"
               PlacementTarget="{Binding ElementName=btnLearn}">
            <TextBlock Text="Julius Caesar was a Roman emperor who lived from 100 BC to 44 BC"
                        Background="AntiqueWhite"
                        Padding="5" Width="150"
                        TextWrapping="Wrap"/>
        </Popup>
    </StackPanel>

877-001

Advertisements

#375 – Binding Something in a Tooltip to a Property on the Parent Control

You can use data binding to bind the value of a simple Tooltip property to some other property of the control.  But you might also want to use data binding when you create a Tooltip as a child element in XAML.

Suppose you want a Tooltip to include several labels and you want the Content of the second label to bind back to a property on the parent control.

You can do this by using the PlacementTarget of the Tooltip to find its parent and then set the DataContext of the Tooltip.

        <TextBox Text="Now is the winter of our discontent etc"
            Width="100" Margin="10">
            <TextBox.ToolTip>
                <ToolTip DataContext="{Binding Path=PlacementTarget, RelativeSource={x:Static RelativeSource.Self}}">
                    <StackPanel>
                        <Label FontWeight="Bold" Content="Full Text"/>
                        <Label Content="{Binding Text}"/>
                        <Label Content="--Gloster, in Richard III (Act I, Scene I)"/>
                    </StackPanel>
                </ToolTip>
            </TextBox.ToolTip>
        </TextBox>