我想创建一个具有不同单元格大小的网格视图。但由于内置的窗口功能,单元格在行中自行调整,我得到以下结果。
但是我希望得到一个网格,其功能类似于android中的交错网格,如下所示:
https://dzone.com/articles/how-implement-staggered-grid
在WP8.1编程中有没有办法做到这一点?
答案 0 :(得分:0)
在xaml中使用ItemsControl表示可用于呈现项集合的控件。
创建一个可用于任何ItemsControl的新面板。有关更多信息,请参阅此链接:http://www.visuallylocated.com/post/2015/02/20/Creating-a-WrapPanel-for-your-Windows-Runtime-apps.aspx
在xaml.cs中编写一个类,如下所示。
public class WrapPanel : Panel
{
protected override Size MeasureOverride(Size availableSize)
{
// Just take up all of the width
Size finalSize = new Size { Width = availableSize.Width };
double x = 0;
double rowHeight = 0d;
foreach (var child in Children)
{
// Tell the child control to determine the size needed
child.Measure(availableSize);
x += child.DesiredSize.Width;
if (x > availableSize.Width)
{
// this item will start the next row
x = child.DesiredSize.Width;
// adjust the height of the panel
finalSize.Height += rowHeight;
rowHeight = child.DesiredSize.Height;
}
else
{
// Get the tallest item
rowHeight = Math.Max(child.DesiredSize.Height, rowHeight);
}
}
// Just in case we only had one row
if (finalSize.Height == 0)
{
finalSize.Height = rowHeight;
}
return finalSize;
}
protected override Size ArrangeOverride(Size finalSize)
{
Rect finalRect = new Rect(0, 0, (finalSize.Width / 2) - 10, finalSize.Height);
double EvenItemHeight = 0;
double OddItemHeight = 0;
int itemNumber = 1;
foreach (var child in Children)
{
if (itemNumber % 2 == 0)
{
finalRect.X = (finalSize.Width / 2);
finalRect.Y = EvenItemHeight;
EvenItemHeight += Children[itemNumber - 1].DesiredSize.Height;
}
else
{
finalRect.X = 0;
finalRect.Y = OddItemHeight;
OddItemHeight += Children[itemNumber - 1].DesiredSize.Height;
}
itemNumber++;
child.Arrange(finalRect);
}
return finalSize;
}
}
StaggerGrid.xaml代码如下: xmlns:local =“using:StaggerGridSample.Views”//类WrapPanel的命名空间
<Grid>
<ScrollViewer >
<ItemsControl x:Name="ItemsControl" ItemsSource="{Binding StrList,UpdateSourceTrigger=PropertyChanged}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<local:WrapPanel/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Background="Red"
Width="185"
VerticalAlignment="Top"
Margin="0,0,6,0">
<TextBlock Text="{Binding}"
VerticalAlignment="Top"
TextWrapping="Wrap"
FontSize="20"/>
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</Grid>