C# 在 ItemsControl DataTemplate 中设置 Canvas 属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1265364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 14:25:05  来源:igfitidea点击:

Setting Canvas properties in an ItemsControl DataTemplate

c#wpfxamlcanvasitemscontrol

提问by atsjoo

I'm trying to databind to this ItemsControl:

我正在尝试对此进行数据绑定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 Nodeelements on the Canvascorrectly:

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

<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?

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

采纳答案by Arcturus

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

附加属性仅适用于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>