You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AvaloniaUI中如何将矩形集合绑定到Canvas并设置位置?

Avalonia中ItemsControl绑定Canvas定位的正确实现

在Avalonia里,ItemsControl没有WPF中的ItemContainerStyle属性,要给Canvas中的项设置定位,得用ItemContainerTheme来替代。

修正后的XAML代码

<ItemsControl Grid.Row="1" Items="{Binding Rectangles}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>

    <ItemsControl.ItemContainerTheme>
        <Style TargetType="ContentPresenter">
            <Setter Property="Canvas.Left" Value="{Binding X}" />
            <Setter Property="Canvas.Top" Value="{Binding Y}" />
        </Style>
    </ItemsControl.ItemContainerTheme>

    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Rectangle Fill="Red" Width="{Binding Width}" Height="{Binding Height}"></Rectangle>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

核心说明

  • Avalonia用ItemContainerTheme实现WPF里ItemContainerStyle的功能,专门用来定义ItemsControl每个项的容器(也就是ContentPresenter)样式
  • Canvas的Left/Top附加属性只对它的直接子元素生效,而ItemsControl的每个项默认被ContentPresenter包裹,所以必须给ContentPresenter设置这两个属性,内部的Rectangle才能正确定位
  • 你的ViewModel代码和Rectangles集合定义不需要做任何修改,保持原样即可

内容的提问来源于stack exchange,提问作者92carmnad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 10:07:24