问题
I have collection of data items that should be represented on a page in a row.
<ItemsControl ItemsSource="{x:Bind ViewModel.PresetsSecondLine, Mode=OneWay}"
Visibility="{x:Bind ViewModel.IsExpanded, Converter={StaticResource BooleanToVisibilityConverter}, Mode=OneWay}"
VerticalAlignment="Stretch"
HorizontalAlignment="Stretch"
Margin="0 5">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapGrid Orientation="Horizontal"
HorizontalChildrenAlignment="Stretch"
MaximumRowsOrColumns="4" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate x:DataType="entities:Preset">
<controls:PresetButtonControl Preset="{x:Bind}"
VerticalAlignment="Stretch"
Width="290"
Margin="5"
Style="{StaticResource DashboardButtonStyle}"
HorizontalAlignment="Stretch" />
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="HorizontalAlignment" Value="Stretch"/>
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
The collection might contain from zero to 4 items displayed in a row. If there are 4 items, they should fill whole row. When there are less than 4 items they should be displayed proportionally:
I found the solution of such issue with UniformGrid, unfortunately UniformGrid is not longer supported in UWP.
回答1:
1) The first easy solution is to use ViewBox which is much like UniformGrid. You can use as below:
<Viewbox Stretch="Uniform" MaxHeight="60" MaxWidth="200">
<StackPanel Orientation="Horizontal">
<Rectangle Fill="Red" Margin="5" Height="50" Width="50"/>
<Rectangle Fill="Red" Margin="5" Height="50" Width="50"/>
<Rectangle Fill="Red" Margin="5" Height="50" Width="50"/>
</StackPanel>
</Viewbox>
2) Or you can choose VariableSizedWrapGrid, which is a layout panel that supports arranging child elements in rows and columns. Each child element can span multiple rows and columns. You can find detail info on MSDN. Below is a simple example.
<VariableSizedWrapGrid Orientation="Horizontal" MaxWidth="150" >
<Rectangle Fill="Red" Margin="5" Height="50" Width="50"/>
<Rectangle Fill="Red" Margin="5" Height="50" Width="50"/>
<Rectangle Fill="Red" Margin="5" Height="50" Width="50"/>
<Rectangle Fill="Red" Margin="5" Height="50" Width="50"/>
<Rectangle Fill="Red" Margin="5" Height="50" Width="50"/>
<Rectangle Fill="Red" Margin="5" Height="50" Width="50"/>
</VariableSizedWrapGrid >
Actually there are still more other ways for adaptive UI. But the above two seem more straight forward and easy.
Let me know if anything unclear.
来源:https://stackoverflow.com/questions/33351737/stretching-buttons-in-itemscontrol