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

如何实现GridView控件中项的文本居中对齐?

实现GridView项文本居中对齐的方法

要让GridView中每个项的文本居中,你需要自定义ItemTemplate——默认的项模板不会自动设置文本居中。以下是修改后的完整代码:

namespace Notenmanager
{
    public class YearPageInitializer
    {
        public static void initialyze(Page page, string year)
        {
            GridView gridView = new ();

            ObservableCollection<string> grades = new ObservableCollection<string>();
            grades.Add("Deutsch 6");
            gridView.ItemsSource = grades;

            gridView.HorizontalAlignment = HorizontalAlignment.Center;
            gridView.VerticalAlignment = VerticalAlignment.Top;

            // 构建自定义项模板,实现文本居中
            var dataTemplate = new DataTemplate();
            var textBlockFactory = new FrameworkElementFactory(typeof(TextBlock));
            
            // 绑定数据源中的字符串到TextBlock的Text属性
            textBlockFactory.SetBinding(TextBlock.TextProperty, new Binding());
            
            // 让文本在TextBlock内部水平居中
            textBlockFactory.SetValue(TextBlock.HorizontalTextAlignmentProperty, TextAlignment.Center);
            
            // 让TextBlock在GridView项的容器内水平居中
            textBlockFactory.SetValue(TextBlock.HorizontalAlignmentProperty, HorizontalAlignment.Center);
            
            dataTemplate.VisualTree = textBlockFactory;
            gridView.ItemTemplate = dataTemplate;

            var grid = page.FindName("g") as Grid;
            grid.Children.Add(gridView);
        }
    }
}

核心要点:

  • 自定义ItemTemplate是关键,默认模板仅用基础TextBlock显示文本,未做居中设置。
  • HorizontalTextAlignment控制文本在TextBlock内部的对齐,HorizontalAlignment控制TextBlock在项容器中的位置,两者配合实现完整的居中效果。
  • 如果是XAML优先的开发模式,也可以在XAML中直接定义ItemTemplate,效果一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 01:45:04