views:

442

answers:

2

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.

A: 

Define a Template with Button and Line positioned at right places wherever you like and then use this Template at the place of Button.

viky
Sorry I did not specify--I cannot use a template because I want to bind both the start and end points. I want the line drawn between two arbitrary elements.
emddudley
+1  A: 

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"&gt;
<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!

viky
I ended up doing the drawing in my code-behind file so that I could do some calculations for the positions, rather than just the corner of the elements.
emddudley