我想使用ItemsControl爲Grid.Row和Grid.Column使用不同的X和Y值來填充網格,我從我的WPF項目中複製它,並且可以在Silverlight(Windows Phone)中無法使用它。ItemsControl Grid.Row Grid.Column在Silverlight中的綁定
這裏是它的簡化版本:
視圖模型,其在DataContext設置爲:
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>
這是結果(它置於所有橢圓在彼此之上):
雖然它應該這樣做:
有誰知道爲什麼不起作用?
什麼時候您的視圖模型被置?在InitializeComponent之前還是之後? –
@ShawnKendrot在 – Jesse
之後ViewModel(DataContext)需要在** InitializeComponent之前設置**。 X和Y的值需要設置爲綁定 –