我正在尝试使用 ItemsControl 为 Grid.Row 和 Grid.Column 使用不同的 X 和 Y 值填充网格,我从我的 WPF 项目中复制了它,但无法让它在 Silverlight (Windows Phone) 中工作。
这是它的简化版本:
DataContext 设置为的 ViewModel:
public class ViewModel
{
public ObservableCollection<GridItem> Data { get; set; }
public ViewModel()
{
Data = new ObservableCollection<GridItem>();
FillData();
}
// fill Data property with some random color GridItems
private void FillData()
{
string[] colors = { "Red", "Green", "Yellow", "Blue" };
Random r = new Random();
for (int i = 0; i < 10; i++)
{
Data.Add(new GridItem(i, i, colors[r.Next(colors.Length)]));
}
}
}
public class GridItem
{
public int X { get; set; }
public int Y { get; set; }
public string Color { get; set; }
public GridItem(int x, int y, string color)
{
X = x;
Y = y;
Color = color;
}
}
XAML:
<Grid x:Name="LayoutRoot" Background="Transparent">
<ItemsControl ItemsSource="{Binding Data}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid Background="Orange">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
</Grid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Ellipse
Grid.Row="{Binding Y}"
Grid.Column="{Binding X}"
Fill="{Binding Color}"
Stroke="White" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
这是结果(它将所有椭圆放在彼此之上):
虽然它应该这样做:
有谁知道为什么这不起作用?