Search code examples
wpfxamlbindingwpf-positioning

Bind a value to a control's absolute position in XAML


Is there a way to bind a value to the absolute position of a control using XAML?

I have a Line element that I would like to be drawn between two Buttons in my application. I was thinking that binding the starting point of the Line to the position of the Button would be the easiest way to make this happen, using RelativeSource somehow.


Solution

  • It seems you want something like this:

    <UserControl x:Class="PracticeSample.MyButton"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <Button x:Name="button" Content="Add" HorizontalAlignment="Center" VerticalAlignment="Top"/>
        <Line Stroke="Black" X1="0" Y1="0" HorizontalAlignment="Center" X2="{Binding ElementName=button, Path=ActualWidth}" Y2="{Binding ElementName=button, Path=ActualHeight}"/>
    </Grid>
    

    use this MyButton in your pages in place of Button,

    Edit: if you want to draw line between two controls don't use above code sample but try this directly in your page:

    <Canvas HorizontalAlignment="Left" Margin="10">
        <Button x:Name="button2" Content="Add" Canvas.Left="10" Canvas.Top="5"/>
        <Button Name="button" Content="Refresh Control" Canvas.Left="100" Canvas.Top="50"/>
        <Line Stroke="Black" X1="{Binding Path=(Canvas.Left),ElementName=button2}" Y1="{Binding Path=(Canvas.Top), ElementName=button2}" X2="{Binding (Canvas.Left), ElementName=button}" Y2="{Binding (Canvas.Top), ElementName=button}"/>
    </Canvas>
    

    Hope this helps!