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

继承ListBoxItem自定义多边形列表项后三角形无法显示的问题求助

继承ListBoxItem自定义多边形列表项后三角形无法显示的问题求助

嗨,我看了你遇到的问题,咱们一步步来排查和解决:

问题根源分析

1. 错误继承ListBoxItem导致ItemTemplate失效

你让PolygonItem继承了ListBoxItem,但ListBox的工作机制是:

  • 如果ItemsSource里的对象不是ListBoxItem,它会自动为每个对象包装一个ListBoxItem容器;
  • 如果对象本身就是ListBoxItem,它会直接使用这个对象作为列表项,完全忽略你定义的ItemTemplate。
    这就是你看不到三角形的核心原因——你的DataTemplate根本没被执行!

2. 多余的PointCollectionConverter

WPF的Polygon.Points属性本身就支持直接绑定PointCollection类型,不需要手动转成字符串再解析回来,这个转换器不仅没用,还可能引入字符串解析的潜在错误。

修复后的代码示例

1. 修改PolygonItem为普通数据类

// 不需要继承ListBoxItem,做纯数据类即可
public class PolygonItem
{
    public double Width { get; set; }
    public double Height { get; set; }
    public PointCollection Points { get; set; }
}

2. 更新ViewModel的初始化逻辑

public ObservableCollection<PolygonItem> PolygonItems { get; set; }

public MainViewModel()
{
    PolygonItems = new ObservableCollection<PolygonItem>()
    {
        new PolygonItem
        {
            Width = 100,
            Height = 100,
            Points = new PointCollection
            {
                new Point(40, 40),
                new Point(100, 40),
                new Point(70, 100),
            }
        },
    };
}

3. 简化XAML,移除多余转换器

<Grid>
    <ListBox ItemsSource="{Binding PolygonItems}" Width="300" Height="300">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Polygon Width="{Binding Width}"
                         Height="{Binding Height}"
                         Points="{Binding Points}"
                         Stroke="Black" Fill="Aquamarine"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

修复说明

现在PolygonItem是普通的数据类,ListBox会自动为每个项生成ListBoxItem容器,同时使用你定义的ItemTemplate渲染多边形。直接绑定PointCollection也避免了转换器带来的风险,这样你的三角形就能正常显示啦!

备注:内容来源于stack exchange,提问作者FelixFeuerdorn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.22 15:39:50