【问题标题】:Setting Canvas properties in an ItemsControl DataTemplate在 ItemsControl DataTemplate 中设置 Canvas 属性
【发布时间】:2010-11-18 22:02:44
【问题描述】:

我正在尝试将数据绑定到这个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>

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

【问题讨论】:

    标签: c# wpf xaml canvas itemscontrol


    【解决方案1】:

    附加属性仅适用于Canvas 的直接子代。 ItemsControl 会将 ContentPresenter 控件作为其直接子元素,因此您可能还需要为其添加样式:

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

    【讨论】:

    • 谢谢。大约 5 分钟前,我自己找到了这个解决方案。我想我发布这个问题有点快。 :)
    • 呵呵.. 我也喜欢那些 AHA 时刻 ;).. 不过也不是很糟糕.. 也许你的问题有一天也能帮助其他人.. 你永远不会知道!跨度>
    • @skb 我也有同样的问题,有没有 Silverlight 解决方法?
    • 如果我的 X 和 Y 位置应该在 ItemsSource 的对象之一内怎么办?我的 ItemsSource 中有一个 Point 对象。
    • 我找到了 Metro/UWP 应用的解决方法 - stackoverflow.com/a/37821355/3431319
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多