oriba
Topic Author
Posts: 3
Joined: 05 Jun 2021, 20:05

Line between two ui elements

18 Mar 2022, 16:00

Hey,

I am having some issues regarding creating lines that binds to the position of UI elements to create a line between the two.
Essentially, I have an element in the center of my UI. Then I also have an ItemsControl that create X amount of UI elements. For each of these
UI elements the ItemsControl generate, I want to create a line between that element and the element in the center of my UI.

Initially I tried doing this by binding to Canvas.Left and Canvas.Top, but that didn't seem to work for me. The binding didn't evaluate to a value, possibly because it's a TemplateLocal value?.
Is there a way to bind to positions of UI elements when creating a Line?

Thanks!
 
User avatar
jsantos
Site Admin
Posts: 4823
Joined: 20 Jan 2012, 17:18
Contact:

Re: Line between two ui elements

28 Mar 2022, 22:41

Could you please paste the XAML here and indicate the exact behavior you are after? Thank you!
 
User avatar
sfernandez
Site Admin
Posts: 3364
Joined: 22 Dec 2011, 19:20

Re: Line between two ui elements

04 Apr 2022, 12:03

Hi oriba,

Items generated by an ItemsControl have two layers, the container control and the ItemTemplate. The panel uses the properties in the container control to layout the items, so if you have a DataTemplate to render lines for each item you have to reference the container properties in the binding ot just bind to the same properties used by the container.

If you want to draw lines that go from each item to the center of the items panel I recommend you use a Grid and that items are centered with [0,0] coordinates (negative X to the left and negative Y above the center):
<Grid
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Grid.Resources>
    <ItemsPanelTemplate x:Key="panelTemplate">
      <Grid/>
    </ItemsPanelTemplate>
    <Style x:Key="containerStyle" TargetType="ContentPresenter">
      <Setter Property="HorizontalAlignment" Value="Center"/>
      <Setter Property="VerticalAlignment" Value="Center"/>
    </Style>
    <DataTemplate x:Key="itemTemplate">
      <Canvas>
        <Line X1="{Binding PosX}" Y1="{Binding PosY}" X2="0" Y2="0" Stroke="Black"/>
      </Canvas>
    </DataTemplate>
  </Grid.Resources>
  <ItemsControl ItemsSource="{Binding Objects}"
    ItemsPanel="{StaticResource panelTemplate}"
    ItemContainerStyle="{StaticResource containerStyle}"
    ItemTemplate="{StaticResource itemTemplate}"/>
</Grid>
Is that what your are looking for?

Who is online

Users browsing this forum: Bing [Bot] and 1 guest