通过DataGrid中的按钮's单击事件检索行号

本文关键字:单击 事件 检索 DataGrid 按钮 通过 | 更新日期: 2023-09-27 18:15:20

我正在向DataGrid的第一列添加一个标签和两个按钮:

//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_eventnext_event方法中,我尝试过:

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

尝试获取DockPanel的父节点触发NullReferenceException

通过DataGrid中的按钮's单击事件检索行号

当您在DataGrid中使用Button时,被单击按钮的行将自动被选中。所以你可以选择DataGrid的SelectedIndex