Search code examples
c#wpfwpf-controlsitemscontrol

How to align the columns of an ItemsControl control (WPF)


I have defined a ItemsControl control in xaml as follows:

<ItemsControl BorderThickness="0"  Name="SummaryList">
</ItemsControl>

In the same xaml file, I've defined the following DateTemplate for each item in the ItemsControl:

<DataTemplate DataType="{x:Type app:UpgradeItem}">
    <StackPanel Orientation="Horizontal">
        <Label Margin="5,5" Content="{Binding Path=ItemText,Mode=OneTime}" />
        <Label Margin="5,5" Content="{Binding Path=FromVersion,Mode=OneTime}" />
        <Label Margin="5,5" Content="{Binding Path=ToVersion,Mode=OneTime}" />
    </StackPanel>
</DataTemplate>

I have bound the ItemsControl's ItemSource to a generlic list of UpgradeItems (i.e. List) and programmatically add to this list during execution. The items in the ItemsControl control populate correctly except that the data in the columns are not aligned. How can I modify this so that the three separate columns (ItemText, FromVersion and ToVersion) are aligned?

TIA


Solution

  • Part of what makes this tricky is that the ItemsControl doesn't have "columns": the control itself has no idea how its items' contents are laid out in relation to each other.

    Your best bet would probably be to use one of the subclasses of ItemsControl that does support columnar data, such as ListView/GridView or the full-fledged DataGrid.