Setting Canvas properties in an ItemsControl DataTemplate

24,996

The attached properties only work on direct children of the Canvas. ItemsControl will place ContentPresenter controls as its direct children, so you might want to add a style for that as well:

<ItemsControl ItemsSource="{Binding Path=Nodes}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemContainerStyle>
        <Style TargetType="ContentPresenter">
            <Setter Property="Canvas.Left" Value="{Binding Path=XPos}" />
            <Setter Property="Canvas.Top" Value="{Binding Path=YPos}" />
        </Style>
    </ItemsControl.ItemContainerStyle>
</ItemsControl>
Share:
24,996

Related videos on Youtube

atsjoo
Author by

atsjoo

Anders

Updated on May 23, 2020

Comments

  • atsjoo
    atsjoo almost 4 years

    I'm trying to databind to this ItemsControl:

    <ItemsControl ItemsSource="{Binding Path=Nodes, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Canvas />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>
    

    By using this DataTemplate, I'm trying to individually position my Node elements on the Canvas correctly:

    <DataTemplate DataType="{x:Type Model:EndNode}">
        <Controls:EndNodeControl Canvas.Left="{Binding Path=XPos}" Canvas.Top="{Binding Path=YPos}" />
    </DataTemplate>
    

    However, it's not working as expected. All my node elements are drawn on top of each other in the same position. Any suggestions on how to accomplish this?

  • atsjoo
    atsjoo almost 15 years
    Thank you. I found this solution myself about 5 minutes ago. I guess I was a bit quick on posting the question. :)
  • Arcturus
    Arcturus almost 15 years
    Hehe.. I love those AHA moment as well ;).. And its not all bad though.. Perhaps can your question help other people too one day.. You'll never know!
  • Rune Jacobsen
    Rune Jacobsen over 14 years
    It helped here as well, +1 for all. :)
  • themaestro
    themaestro almost 13 years
    @skb I have the same problem, is there a Silverlight workaround for this?
  • El Mac
    El Mac almost 9 years
    What if my X and Y Position should be inside one of the objects of ItemsSource? I got a Point object in my ItemsSource.
  • Arctic Vowel
    Arctic Vowel almost 8 years
    I found a workaround for metro/UWP apps - stackoverflow.com/a/37821355/3431319
  • Dominic Jonas
    Dominic Jonas over 5 years
    @ElMac <Setter Property="Canvas.Left" Value="{Binding RelativeSource={RelativeSource Self}, Path=XPos}" />