c# - 在 ItemsControl DataTemplate 中设置 Canvas 属性

标签 c# wpf xaml canvas itemscontrol

我正在尝试将数据绑定(bind)到此 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>

但是,它没有按预期工作。我所有的节点元素都在同一位置彼此重叠绘制。关于如何实现这一点有什么建议吗?

最佳答案

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

关于c# - 在 ItemsControl DataTemplate 中设置 Canvas 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1265364/

相关文章:

c# - 与转换器的双向数据绑定(bind)不更新源

c# - MySQL 服务器错误 - 您的 SQL 语法有错误

WPF 数据网格 : Binding DataGridColumn visibility to ContextMenu MenuItems IsChecked (MVVM)

c# - "LINQ to Entities", "LINQ to SQL"和 "LINQ to Dataset"有什么区别

c# - 如何以编程方式更改 Active Directory 密码

c# - WPF ListBoxItem MVVM 中的 SelectedItem 问题

c# - 更改主窗口名称后出错

c# - 如何拥有照片查看器风格的页面?

c# - 使 WPF TextBox 绑定(bind)触发每个新角色?

xaml - 两种纵横比的两种布局 (4 :3 and 16:9) - changing automatically