views:

24

answers:

1

I have a canvas which contains specific usercontrols.

At some point, I want to add a line to the canvas (in code) where one of the points is bound to the position of an element in a usercontrol. The usercontrol is dynamic, so elements can change position.

The usercontrol contains a layout with grids, stackpanels etc. that the element can be located in.

For the usercontrol, I'd get the Canvas.Left and Canvas.Top property, but since I don't want to bind to the usercontrol but to an element it contains, how would I do that ? (In a way that if the usercontrol's layout changes, the new position of the element is taken into account)

+1  A: 

Let's stipulate that there are 3 things here:

"Line" is being bound to "Child" who is contained by "Parent".

Line should set its Canvas.Top and Canvas.Left to a Binding on Child, using a ValueConverter who needs to have access to Parent.

The ValueConverter will return Parent.Left + Child.GetPosition(Parent).Left

(Or whatever the exact lookup methods are). The important thing is that the Child gets its position relative to the Parent, and adds in the Parent's position.

(Elaborating post comment) So you specify a line this way:

<Line X1="50" Y1="50" X2="200" Y2="200" />

Which means that you apply a binding to each of those coordinate specifiers. Probably your best bet is to pass the X or Y to the ValueConverter as a ConverterParameter, to save you writing too much duplicate code.

Your original question specifies that you are looking for X1,Y1. I don't know what you want the other end of the line to be, it sounds like it's fixed somewhere. Or if it's going to another element you do basically the same trick there - this is going to work for one point only. Let's assume for the moment that you always want the other point to be 100,100.

So your line is specified like this:

<Line X1="{Binding ElementName=yourTarget, ConverterParameter=X, Converter={StaticResource targetLocationExtractor}}" Y1="{Binding ElementName=yourTarget, ConverterParameter=Y, Converter={StaticResource targetLocationExtractor}}" X2="200" Y2="200" />
Chris Hagan
Thanks for your response.A WPF Line has X1,Y1-X2,Y2 points which should be bound.Can you elaborate a bit more on how I'd do that ?
IUsedToBeAPygmy