Setting Canvas properties in an ItemsControl DataTemplate

C#WpfXamlCanvasItemscontrol

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionatsjooView Question on Stackoverflow
Solution 1 - C#ArcturusView Answer on Stackoverflow