我正在尝试使用wpf来制作扫雷游戏。我设计的游戏板为用下面的代码按钮的网格:获取由一个ItemsControl填充的Grid和Colum位置
<Window.Resources>
<DataTemplate x:Key="DataTemplateLevel2">
<Button Content="{Binding}" Height ="30" Width="40" Click ="Execute"/>
</DataTemplate>
<DataTemplate x:Key ="DataTemplateLevel1">
<ItemsControl ItemsSource ="{Binding}" ItemTemplate="{DynamicResource DataTemplateLevel2}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</DataTemplate>
</Window.Resources>
<Grid>
<ItemsControl x:Name ="Field" ItemTemplate="{DynamicResource DataTemplateLevel1}" />
</Grid>
和
List<List<int?>> buttonGrid = new List<List<int?>>();
for (int r = 0; r < Rows; r++)
{
buttonGrid.Add(new List<int?>());
for (int c = 0; c < Cols; c++)
{
buttonGrid[r].Add(null);
}
}
InitializeComponent();
Field.ItemsSource = buttonGrid;
。
问题是,当我点击一个按钮,我的事件处理程序需要知道按钮的行和列,但Grid.GetRow
和Grid.GetColumn
总是返回0.我认为这是因为网格只包含一个ItemsControl。如何获得有意义的行和列值,同时仍然允许动态网格大小?
ItemsControl的子项不是网格的直接子元素。您可以整天给它们使用Grid.Row和Grid.Column值,并且它不会起作用,因为它们不是定义了多行和多列的Grid的子项。相反,它们是由'ItemsPanelTemplate'创建的StackPanel的子项。没有网格。只有StackPanel。你想在这里做什么? –
由于网格不会提供索引,我想从ItemsControls获取索引。点击事件处理程序知道哪个按钮被按下,我只是不知道如何询问ItemsControl的位置。 – Kevlarz