Search code examples
c#listviewuwpuwp-xamllistviewitem

Incorrect content alignment inside ListView


I am working on UWP app and I found issue with content alignment inside the ListView. As doc say, we should use ListView.VerticalContentAlignment property to align content, but I find out, that the property is ignored and default value is used instead.

For example this simple app:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <ListView ItemsSource="{x:Bind Data}" VerticalContentAlignment="Top">
        <ListView.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal" />
            </ItemsPanelTemplate>
        </ListView.ItemsPanel>
        <ListView.ItemTemplate>
            <DataTemplate x:DataType="x:String">
                <TextBlock Text="{x:Bind}" />
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Grid>

Where code behind is just this:

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
    }


    public List<string> Data { get; set; } = new List<string>()
    {
        "a","b","c","d","e"
    };
}

Have following output: enter image description here

Althougth the ListView.VerticalContentAlignment is set. I check the ListViewItemPresenter (TextBlock container) in Live Visual Tree and default value is there, but ignored and ListViewItemPresenterVerticalContentAlignment used instead.

enter image description here

The Microsoft doc say, that I should use ContentPresenter.VerticalContentAlignmentProperty instead of ListViewItemPresenterVerticalContentAlignmentProperty. Is it just bug, or am I doing something wrong? Is there way to fix the issue?


Solution

  • maybe you can try to modify the ItemContainerStyle like this:

    <ListView ...>
      <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
          <Setter Property="HorizontalContentAlignment" Value="Stretch" />
          <Setter Property="VerticalContentAlignment" Value="Top" />
        </Style>
      </ListView.ItemContainerStyle>
    </ListView