Wpf在按钮上获取DataGrid的行号,单击偶数C#

Wpf在按钮上获取DataGrid的行号,单击偶数C#,c#,wpf,datagrid,C#,Wpf,Datagrid,我在DataGrid的每一行中都有2个按钮。它们将用于保存编辑的行信息或删除行。但我无法在单击事件时检索行号。 (关于stackoverflow,我也有类似的问题,但没有一个对我有效) 如果固定在事件上,我将使用绑定来检索数据项及其索引 在事件处理程序中: var btn = sender as Button; var item = btn.GetBindingExpression(Button.DataContextProperty).DataItem as YourRowItemClass;

我在DataGrid的每一行中都有2个按钮。它们将用于保存编辑的行信息或删除行。但我无法在单击事件时检索行号。 (关于stackoverflow,我也有类似的问题,但没有一个对我有效)


如果固定在事件上,我将使用绑定来检索数据项及其索引

在事件处理程序中:

var btn = sender as Button;
var item = btn.GetBindingExpression(Button.DataContextProperty).DataItem as YourRowItemClass;
var index = YourViewModel.ItemCollection.IndexOf(item);
视图模型:

class YourViewModel : INotifyPropertyChanged {
    ObservableCollection<RowItem> ItemCollection { get; private set; }
}

什么是ViewModel?我查看了MVVM实践,但不明白我应该在这里引用什么。我假设您正在使用
ItemsSource
制作
DataGrid
行。如果您对MVVM不太熟悉,您仍然可以找到大量关于它的资源,并且可能超出了范围w.r.t这个问题太笼统了。请参见显示示例视图模型代码的编辑(此示例不需要界面本身,但通常附带该界面)。
class YourViewModel : INotifyPropertyChanged {
    ObservableCollection<RowItem> ItemCollection { get; private set; }
}
DataContext="{Binding}"