在 ItemsControl DataTemplate 中设置 Canvas 属性 [英] Setting Canvas properties in an ItemsControl DataTemplate

查看:35
本文介绍了在 ItemsControl DataTemplate 中设置 Canvas 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数据绑定到这个 ItemsControl:

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>

通过使用这个 DataTemplate,我试图在 Canvas 上正确地单独定位我的 Node 元素:

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?

推荐答案

附加属性仅适用于 Canvas 的直接子级.ItemsControl 会将 ContentPresenter 控件作为其直接子控件放置,因此您可能还想为其添加样式:

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>

这篇关于在 ItemsControl DataTemplate 中设置 Canvas 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆