Search code examples
xamltext-alignmentmaui

HorizontalTextAlignment Element in a Maui xaml file, does not change the Alignment of the text


I am currently working on a UI for an application and I want to align the following label Text automatically horizontally, so I wanted to test, how I can align text normally. The Label Documentation of Maui state, that I have to do it with the HorizontalTextAlignment Element. I tried it several times and it worked, but here it won't:

    <CollectionView Grid.Row="1" BackgroundColor="Black">
        <CollectionView.ItemsSource>
            <x:Array Type="{x:Type models:MessageModel}">
                <models:MessageModel Message="Hallo" Created="01.01.2001 00:00:00"/>
                <models:MessageModel Message="Hey na!" Created="01.01.2001 00:00:00"/>
            </x:Array>
        </CollectionView.ItemsSource>
        <CollectionView.ItemTemplate>
            <DataTemplate x:DataType="models:MessageModel">
                <Label HorizontalTextAlignment="End" TextColor="White" Text="{Binding Created}"/>
            </DataTemplate>
        </CollectionView.ItemTemplate>
    </CollectionView>

The Output is the following (And yeah I could use one Label, but I wanted to try both ways):Output Edit: adding the following Element HorizontalOptions="FillAndExpand" at the label + a Background Color: Edit Pic Output Edit2: Edit2


Solution

  • I fix it by handle Loaded event on page.

    Loaded += LoginPage_Loaded;
    

    In loaded hanlder add line, which change align (by defalut it start or end):

    private void LoginPage_Loaded(object sender, EventArgs e)
    {
        Label.HorizontalTextAlignment = TextAlignment.Center;
    }