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

如何在WPF中自定义带三角形的ListBoxItem控件并构建2D场

实现带三角形的自定义ListBoxItem并构建2D场

1. 创建自定义ListBoxItem控件

首先定义继承自ListBoxItem的控件类,指定默认样式键:

public class TriangleListBoxItem : ListBoxItem
{
    static TriangleListBoxItem()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(TriangleListBoxItem), 
            new FrameworkPropertyMetadata(typeof(TriangleListBoxItem)));
    }
}

2. 定义控件模板(绘制三角形)

在项目的Generic.xaml中编写控件样式,使用Polygon绘制三角形:

<Style TargetType="{x:Type local:TriangleListBoxItem}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:TriangleListBoxItem}">
                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}"
                        Padding="2">
                    <!-- 三角形坐标:可根据需求调整形状方向和大小 -->
                    <Polygon x:Name="Triangle"
                             Points="0,12 12,0 24,12" 
                             Fill="SteelBlue" 
                             Stroke="Black"
                             StrokeThickness="1"/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

3. 用ListBox搭建2D网格场

修改ListBox的ItemsPanel为UniformGrid,实现项的二维排列:

<ListBox Width="500" Height="500">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <!-- 设置行列数,比如10x10的网格 -->
            <UniformGrid Rows="10" Columns="10"/>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <!-- 批量添加自定义项,或通过绑定数据源生成 -->
    <local:TriangleListBoxItem Margin="1"/>
    <local:TriangleListBoxItem Margin="1"/>
    <!-- 重复添加或绑定集合实现动态生成 -->
</ListBox>

如果需要动态生成大量项,可在ViewModel中创建集合并绑定:

public ObservableCollection<object> FieldItems { get; set; } = new();

// 初始化100个项(10x10网格)
public ViewModel()
{
    for (int i = 0; i < 100; i++)
    {
        FieldItems.Add(new object());
    }
}

XAML中绑定数据源:

<ListBox ItemsSource="{Binding FieldItems}" ...>
    <!-- 保留上述ItemsPanel设置 -->
</ListBox>

4. 可选:添加状态样式

通过触发器实现选中、悬停时的三角形样式变化:

<Style TargetType="{x:Type local:TriangleListBoxItem}">
    <!-- 基础样式设置 -->
    <Setter Property="Background" Value="Transparent"/>
    <Setter Property="Template">
        <!-- 模板内容同上 -->
    </Setter>
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter TargetName="Triangle" Property="Fill" Value="LightSkyBlue"/>
        </Trigger>
        <Trigger Property="IsSelected" Value="True">
            <Setter TargetName="Triangle" Property="Fill" Value="Orange"/>
        </Trigger>
    </Style.Triggers>
</Style>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 04:12:52