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

如何在XAML中简洁定义34个相同的ColumnDefinition?

批量创建34个等宽ColumnDefinition的简便实现方式

以下几种方法可以避免重复编写34次<ColumnDefinition Width="1*"/>:

方法1:后台代码循环创建

在窗口/用户控件的构造函数或Loaded事件中,通过循环向目标Grid的ColumnDefinitions集合添加元素:

// 假设你的Grid控件名为targetGrid
for (int i = 0; i < 34; i++)
{
    targetGrid.ColumnDefinitions.Add(new ColumnDefinition 
    { 
        Width = new GridLength(1, GridUnitType.Star) 
    });
}

方法2:自定义标记扩展(XAML中直接使用)

创建一个自定义MarkupExtension,用来快速生成指定数量的等宽列定义:

后台扩展类代码

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;

namespace YourNamespace
{
    public class ColumnDefinitionsExtension : MarkupExtension
    {
        // 需要生成的列数量
        public int Count { get; set; }
        
        // 列宽,默认值为1*
        public GridLength Width { get; set; } = new GridLength(1, GridUnitType.Star);

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            var columnDefinitions = new ColumnDefinitionCollection();
            for (int i = 0; i < Count; i++)
            {
                columnDefinitions.Add(new ColumnDefinition { Width = Width });
            }
            return columnDefinitions;
        }
    }
}

XAML中使用

先引入对应命名空间(示例中用local指代),然后直接调用扩展:

<Window xmlns:local="clr-namespace:YourNamespace">
    <Grid>
        <Grid.ColumnDefinitions>
            {local:ColumnDefinitions Count=34}
        </Grid.ColumnDefinitions>
    </Grid>
</Window>

方法3:借助ItemsControl绑定生成

通过绑定一个指定长度的集合,让ItemsControl自动生成列定义:

后台准备集合

using System.Collections.ObjectModel;
using System.Linq;

// 在ViewModel或代码后台定义集合
public ObservableCollection<int> ColumnItems { get; set; }

// 构造函数中初始化集合(生成34个元素)
ColumnItems = new ObservableCollection<int>(Enumerable.Range(0, 34));

XAML中绑定

<Grid DataContext="{Binding RelativeSource={RelativeSource Self}}">
    <Grid.ColumnDefinitions>
        <ItemsControl ItemsSource="{Binding ColumnItems}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <ColumnDefinition Width="1*"/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <VirtualizingStackPanel Orientation="Horizontal"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>
    </Grid.ColumnDefinitions>
</Grid>

如果是固定数量的列,自定义标记扩展是最简洁的方案,既能在XAML中直接声明,又能通过修改Count值快速调整列数,维护性更强。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 05:03:19