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

时间:2013-05-24 19:30:03

标签: c# datagrid wpfdatagrid

我在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

1 个答案:

答案 0 :(得分:2)

Button内使用DataGrid时,将自动选择带有单击按钮的行。所以你可以抓住DataGrid的SelectedIndex