C# SelectionChanged未触发WPF

C# SelectionChanged未触发WPF,c#,wpf,xaml,C#,Wpf,Xaml,我正在使用WPF创建一个国际象棋游戏。我需要获取所选单元格(行/列)的索引 XAML: 它允许我获取单元格的列索引 我目前正在尝试: private void chessGrid_SelectionChanged(object sender, SelectionChangedEventArgs e) { y = chessGrid.SelectedIndex; Debug.WriteLine(y); } 去吵架。但是这不起作用,当删除SelectionUnit=“Cell”时,

我正在使用WPF创建一个国际象棋游戏。我需要获取所选单元格(行/列)的索引

XAML:

它允许我获取单元格的列索引

我目前正在尝试:

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获取所选单元格的行/列索引

编辑:要求应用程序使用三层体系结构。

尝试以下方法:

private void dggg_CurrentCellChanged(object sender, EventArgs e)
{
    x = chessGrid.CurrentCell.Column.DisplayIndex;
    y = chessGrid.Items.IndexOf(chessGrid.CurrentCell.Item);
}

你做错了。阅读有关绑定和MVVM的内容。@KostyaK我忘了提到应用程序必须使用三层体系结构编写,我认为MVVM与之不兼容,但我会仔细阅读,谢谢。@Tagor如果您指的是单独的数据访问层、业务逻辑层和表示层,请使用MVVM。以任何其他方式使用WPF都是痛苦和困难的。
private void chessGrid_CurrentCellChanged(object sender, System.EventArgs e)
{
    x = chessGrid.CurrentCell.Column.DisplayIndex;
    y = chessGrid.Items.IndexOf(chessGrid.CurrentCell)
    Debug.WriteLine(x);
}
private void dggg_CurrentCellChanged(object sender, EventArgs e)
{
    x = chessGrid.CurrentCell.Column.DisplayIndex;
    y = chessGrid.Items.IndexOf(chessGrid.CurrentCell.Item);
}