0

我正在填充一个UniformGrid绑定。源是 a Square[,],而UniformGrid是用Button对象填充的。

这是我所做的: 双数组和网格之间的数据绑定

System.InvalidOperationException在尝试这样做时得到一个:

private void OnClickButton(object sender, RoutedEventArgs e)
{
    Button b = (Button)sender;
    UniformGrid grid = ItemControlGrid.ItemsPanel.LoadContent() as UniformGrid;
    int rows = grille.Rows;
    int columns = grille.Columns;
    UIElementCollection children = grid.Children; // I get the Exception here
    int index = children.IndexOf(b);
    int row = index / columns;
    int column = index % rows;
}

这是我的 XAML:

<ItemsControl Background="Gray" Margin="0" Width="800" Height="800"  
    x:Name="ItemControlGrid"
    ItemsSource="{Binding MapGrid}"
    ItemTemplateSelector="{StaticResource selector}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid 
                IsItemsHost="true"
                x:Name="My_UniformGrid" Rows="25" Columns="25"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
 </ItemsControl>

为什么我会得到这个Exception

4

1 回答 1

0

将出现异常的行更改为:

ItemCollection children = ItemControlGrid.Items;

其余的代码应该编译得一样好。我认为grille实际上是grid.

<ItemsControl Background="Gray" Margin="0" Width="800" Height="800"  
    x:Name="ItemControlGrid">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid IsItemsHost="true" Rows="25" Columns="25"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <!-- First two elements are just dummies to test the result-->
    <Control />
    <Image />
    <Button Click="Button_Click_1" />
</ItemsControl>

代码隐藏:

void Button_Click_1(object sender, RoutedEventArgs e)
{
    var b = (Button) sender;
    var grid = ItemControlGrid.ItemsPanel.LoadContent() as UniformGrid;
    var rows = grid.Rows;
    var columns = grid.Columns;
    var children = ItemControlGrid.Items;
    var index = children.IndexOf(b);
    var row = index/columns;
    var column = index%rows;
    //column will be 2
}
于 2013-01-04T18:08:03.777 回答