XAML 对齐gridview项的文本

vecaoik1  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(148)

我想将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);
        }
    }
}

字符串

6jygbczu

6jygbczu1#

而不是一个单一的string,我会创建一个recordclass

public record Grade(string Subject, int Value);

字符串
然后创建一个ItemTemplate与个别TextBlock s,所以我们可以对齐文本:

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);

相关问题