我在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_event
和next_event
方法中:
public void previous_event(object sender, RoutedEventArgs e)
{
Console.WriteLine("prev " + ((DockPanel)((Button)e.OriginalSource).Parent).Parent.GetType());
}
尝试获取DockPanel
的父级会触发NullReferenceException
。
答案 0 :(得分:2)
在Button
内使用DataGrid
时,将自动选择带有单击按钮的行。所以你可以抓住DataGrid的SelectedIndex
。