对齐网格视图项的文本

Align text of gridview items

提问人:Fire Cube 提问时间:11/17/2023 最后编辑:Andrew KeepCodingFire Cube 更新时间:11/17/2023 访问量:37

问:

我想将 GridView 项的文本对齐居中。 我该怎么做?

这是我的代码:

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 \n\n6");
            gridView.ItemsSource = grades;
    
            gridView.HorizontalAlignment = HorizontalAlignment.Center;
            gridView.VerticalAlignment = VerticalAlignment.Top;
    
            var grid = page.FindName("g") as Grid;
            grid.Children.Add(gridView);
        }
    }
}
XAML WinUI-3

评论


答:

1赞 Andrew KeepCoding 11/17/2023 #1

而不是单个 ,我会创建一个或一个:stringrecordclass

public record Grade(string Subject, int Value);

然后创建一个带有单个 S 的 S,以便我们可以对齐文本:ItemTemplateTextBlock

GridView gridView = new();

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

gridView.ItemTemplate = XamlReader.Load(
    """
    <DataTemplate xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
        <StackPanel>
            <TextBlock
                Text="{Binding Subject}"
                HorizontalAlignment="Center" />
            <TextBlock
                Text="{Binding Value}"
                HorizontalAlignment="Center" />
        </StackPanel>
    </DataTemplate>
    """) as DataTemplate;

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