85

我正在尝试对此进行数据绑定ItemsControl

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

通过使用它DataTemplate,我试图将我的Node元素单独定位在Canvas正确的位置:

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

但是,它没有按预期工作。我所有的节点元素都在同一位置相互叠加。关于如何做到这一点的任何建议?

4

1 回答 1

146

附加属性仅适用于Canvas. ItemsControlContentPresenter控件放置为其直接子级,因此您可能还需要为其添加样式:

<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>
于 2009-08-12T10:38:47.473 回答