I’m attempting to display a table of data which looks like this on Windows Phone 7 (thus I don’t have the DataGrid control:
(The columns are: Rank, Score, Win-Loss, Name.)
7 43 22-7 Aaron
2 13 4-7 Beth
5 42 3-1 Clark
And so on. I have used a ListBox with an ItemTemplate to query the values and print them out, with a Grid to format the list. However, each grid entry is separate! I want the columns to all line up, but when an element size is not the same size, it isn’t aligned.
This is the code I am using:
<ListBox x:Name="MyListBox" ItemsSource="{Binding AllPlayers}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Margin="10,0,10,0" Text="{Binding Rank}"/>
<TextBlock Grid.Column="1" Margin="10,0,10,0" Text="{Binding Score}"/>
<StackPanel Grid.Column="2" Margin="10,0,10,0" Orientation="Horizontal">
<TextBlock Grid.Column="2" Text="{Binding Wins}"/>
<TextBlock Grid.Column="2" Text="-"/>
<TextBlock Grid.Column="2" Text="{Binding Losses}"/>
</StackPanel>
<TextBlock Grid.Column="3" Margin="10,0,10,0" Text="{Binding Name}"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Is there a better way to do this? I could set the pixel width on the “Grid” column manually, but I’d rather have it auto-figure out the width, if possible.
Since WP7 supports one fixed screen pixel width, you can set exact width for each column. What width to use – that’s up to you, depending on the content, but that would be the way to keep them all one size.