I want to align the text of the GridView items to center. How can I do this?
Here is my code:
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);
}
}
}
Instead of a single string
, I would create a record
or a class
:
public record Grade(string Subject, int Value);
then create an ItemTemplate
with individual TextBlock
s so we can align the texts:
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);