我正在使用绑定填充UniformGrid
。来源为Square[,]
,UniformGrid
填充了Button
个对象。
这是我做的: Data Binding between a double array and a grid
尝试执行此操作时,我得到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
?
答案 0 :(得分: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
}