C# 通过按钮检索行号';在DataGrid中单击事件

C# 通过按钮检索行号';在DataGrid中单击事件,c#,datagrid,wpfdatagrid,C#,Datagrid,Wpfdatagrid,我正在向数据网格的第一列添加一个标签和两个按钮: //buttons DataGridTemplateColumn dgc = new DataGridTemplateColumn(); DataTemplate dtm = new DataTemplate(); FrameworkElementFactory label = new FrameworkElementFactory(typeof(Label)); label.SetValue(Label.ContentProperty, ne

我正在向数据网格的第一列添加一个标签和两个按钮:

//buttons
DataGridTemplateColumn dgc = new DataGridTemplateColumn();
DataTemplate dtm = new DataTemplate();

FrameworkElementFactory label = new FrameworkElementFactory(typeof(Label));
label.SetValue(Label.ContentProperty, new Binding("Name"));

FrameworkElementFactory button = new FrameworkElementFactory(typeof(Button));
button.SetValue(Button.ContentProperty, "7");
button.SetValue(Button.FontFamilyProperty, new FontFamily("Webdings"));
button.SetValue(Button.HeightProperty, 18.0);
button.AddHandler(Button.ClickEvent, new RoutedEventHandler(previous_event));

FrameworkElementFactory button2 = new FrameworkElementFactory(typeof(Button));
button2.SetValue(Button.ContentProperty, "8");
button2.SetValue(Button.FontFamilyProperty, new FontFamily("Webdings"));
button2.SetValue(Button.HeightProperty, 18.0);
button2.AddHandler(Button.ClickEvent, new RoutedEventHandler(next_event));

FrameworkElementFactory label2 = new FrameworkElementFactory(typeof(Label));
label2.SetValue(Label.ContentProperty, "");

FrameworkElementFactory btnReset = new FrameworkElementFactory(typeof(DockPanel));
btnReset.AppendChild(label);
btnReset.AppendChild(button);
btnReset.AppendChild(button2);
btnReset.AppendChild(label2);

btnReset.SetValue(DockPanel.HorizontalAlignmentProperty, HorizontalAlignment.Right);
btnReset.SetValue(DockPanel.HeightProperty, 24.0);

//set the visual tree of the data template  
dtm.VisualTree = btnReset;
dgc.Header = "Events / Time";
dgc.CellTemplate = dtm;
dgc.Width = 300;

dgTimeline.Columns.Add(dgc);
如何获取单击按钮所在的行号?在
previous\u event
next\u event
中,我尝试了以下方法:

public void previous_event(object sender, RoutedEventArgs e)
{
    Console.WriteLine("prev " + ((DockPanel)((Button)e.OriginalSource).Parent).Parent.GetType());
}

尝试获取
DockPanel
的父级会触发
NullReferenceException

当您在
DataGrid
中使用
按钮时,将自动选择单击按钮的行。因此,您只需获取DataGrid的
SelectedIndex