Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding position of element to another element's bounding box

Tags:

wpf

I have a shape contained in a canvas, and I wish to attach a label to the bottom of the aforementioned shape bounding box. At design time this is trivial, but the shape is meant to be draggable at runtime, and the label should move according to it. I can "manually" modify the label position in the same Shape_Mouse* methods I use to drag the shape, but I think a binding of some sort would be more clean, and probably required if I want to easily add elements and "attach" to the shape at runtime...

XAML

<Canvas x:Name="canv" HorizontalAlignment="Center" Height="531"
        Margin="10,10,0,0" VerticalAlignment="Top" Width="947"
        Background="#FFCDF3EB">
    <Ellipse Fill="#FFF3A7A7" Height="113" Canvas.Left="120" Stroke="Black"
             Canvas.Top="173" Width="125"/>
    <Label Content="Label" Height="39" Canvas.Left="120" Canvas.Top="286"
           Width="125"/>
</Canvas>

So, is there a way to easily bind the position of an element A to the bottom of element B bounding box in WPF?

like image 757
Harter Avatar asked Dec 31 '25 20:12

Harter


2 Answers

You can bind Canvas.Left and Canvas.Top of Label with ellipse so that it moves with shape.

Give x:Name to ellipse and bind using ElementName from Label.

<Ellipse x:Name="ellipse" Fill="#FFF3A7A7" Height="113" Canvas.Left="120"
         Stroke="Black" Canvas.Top="173" Width="125"/>
<Label Content="Label" Height="39"
       Canvas.Left="{Binding (Canvas.Left),ElementName=ellipse}"
       Canvas.Top="286"
       Width="125"/>

Canvas.Top won't be same as that of ellipse. So, what you can do is have converter where you will pass Canvas.Top of ellipse and add some offset to it and bind with Canvas.Top of label just like we did for Canvas.Left.

like image 72
Rohit Vats Avatar answered Jan 06 '26 10:01

Rohit Vats


The simplest way for you to do that is for you to put both the Canvas and the Label into a UserControl. Your UserControl XAML would look something like this:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Canvas Grid.Row="0" ... />
    <TextBlock Grid.Row="1" Text="Some description" ... />
</Grid>

Now, when the user moved the UserControl, both the Canvas and the label will move together and there's no need for any continuous position calculations.

You can find out more by taking a look a the User Control in WPF page on the C# Corner website.

like image 38
Sheridan Avatar answered Jan 06 '26 10:01

Sheridan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!