Reputation: 2115
I am adding a label and two buttons to the first column of a 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);
How do I get the row number in which the clicked button is? In the previous_event
and next_event
methods I have tried:
public void previous_event(object sender, RoutedEventArgs e)
{
Console.WriteLine("prev " + ((DockPanel)((Button)e.OriginalSource).Parent).Parent.GetType());
}
Trying to get DockPanel
's parent triggers a NullReferenceException
.
Upvotes: 0
Views: 1110
Reputation: 6056
When you use a Button
inside a DataGrid
, the row with the clicked button will automatically be selected. So you can just grab the SelectedIndex
of the DataGrid.
Upvotes: 3