我正在使用WPF创建一个国际象棋游戏。我需要获取所选单元格的索引(行/列)。
XAML:
<DataGrid Name ="chessGrid"
AutoGenerateColumns="False"
HeadersVisibility="None"
SelectionMode="Single"
SelectionUnit="Cell"
CanUserAddRows="False"
CanUserDeleteRows="False"
CanUserReorderColumns="False"
CanUserResizeColumns="False"
CanUserResizeRows="False"
CanUserSortColumns="False"
CurrentCellChanged="chessGrid_CurrentCellChanged"
SelectionChanged="chessGrid_SelectionChanged">
<DataGrid.Columns>
<DataGridTextColumn Width="*" Binding="{Binding columns[0]}" />
<DataGridTextColumn Width="*" Binding="{Binding columns[1]}" />
<DataGridTextColumn Width="*" Binding="{Binding columns[2]}" />
<DataGridTextColumn Width="*" Binding="{Binding columns[3]}" />
<DataGridTextColumn Width="*" Binding="{Binding columns[4]}" />
<DataGridTextColumn Width="*" Binding="{Binding columns[5]}" />
<DataGridTextColumn Width="*" Binding="{Binding columns[6]}" />
<DataGridTextColumn Width="*" Binding="{Binding columns[7]}" />
<DataGridTextColumn Width="*" Binding="{Binding columns[8]}" />
<DataGridTextColumn Width="*" Binding="{Binding columns[9]}" />
</DataGrid.Columns>
当一个小区改变后我打电话:
private void chessGrid_CurrentCellChanged(object sender, System.EventArgs e)
{
x = chessGrid.CurrentCell.Column.DisplayIndex;
Debug.WriteLine(x);
}
这允许我获取单元格的列索引。
我目前正在尝试:
private void chessGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
y = chessGrid.SelectedIndex;
Debug.WriteLine(y);
}
获取行。但这不起作用,当删除SelectionUnit =“Cell”时,上述工作,但我当然不能这样做,因为你不能选择整行。我也尝试过:
private void chessGrid_CurrentCellChanged(object sender, System.EventArgs e)
{
x = chessGrid.CurrentCell.Column.DisplayIndex;
y = chessGrid.Items.IndexOf(chessGrid.CurrentCell)
Debug.WriteLine(x);
}
将y设置为-1?
所以我的问题是如何使用简单的WPF和datagrid获取所选单元格的行/列索引?
编辑:要求是应用程序应使用三层架构。
答案 0 :(得分:1)
试试这个:
private void dggg_CurrentCellChanged(object sender, EventArgs e)
{
x = chessGrid.CurrentCell.Column.DisplayIndex;
y = chessGrid.Items.IndexOf(chessGrid.CurrentCell.Item);
}