Reputation: 163
In a C# WPF program I have a grid that I have successfully populated with my data. One column has a button that I want to link to an edit page. The code is below.
var col = new DataGridTemplateColumn();
col.Header = "Edit";
var template = new DataTemplate();
var textBlockFactory = new FrameworkElementFactory(typeof(Button));
textBlockFactory.SetBinding(Button.ContentProperty, new System.Windows.Data.Binding("rumId"));
textBlockFactory.SetBinding(Button.NameProperty, new System.Windows.Data.Binding("rumId"));
textBlockFactory.AddHandler( Button.ClickEvent, new RoutedEventHandler((o, e) => System.Windows.MessageBox.Show("TEST")));
template.VisualTree = textBlockFactory;
col.CellTemplate = template;
template = new System.Windows.DataTemplate();
var comboBoxFactory = new FrameworkElementFactory(typeof(Button));
template.VisualTree = comboBoxFactory;
col.CellEditingTemplate = template;
dgData.Columns.Add(col);
The code successfully runs and I get a message box every time I choose a button.
How can I get this to call another method and then retrieve from this the row number of the button that I chose?
The subsequent method would look something like, how can I call it?
void ButtonClick(object sender, MouseButtonEventArgs e)
{
MessageBox.Show("hi Edit Click 1");
// get the data from the row
string s = myRumList.getRumById(rumid).getNotes();
// do something with s
}
Upvotes: 1
Views: 1010
Reputation: 132558
Just bind the Id
, or better yet the entire data object, as the CommandParameter
void ButtonClick(object sender, MouseButtonEventArgs e)
{
MessageBox.Show("hi Edit Click 1");
Button b = sender as Button;
// Get either the ID of the record, or the actual record to edit
// from b.CommandParameter and do something with it
}
This will also work if you decide to switch your application so it uses the MVVM design pattern. For example, the XAML would look like this:
<Button Command="{Binding EditCommand}"
CommandParameter="{Binding }" />
Upvotes: 1
Reputation: 2364
What I understand is that you need to have the rumId
of the clicked Text block in order to edit it.
While setting the Click
event you can do the following.
textBlockFactory.AddHandler( Button.ClickEvent,
new RoutedEventHandler((o, e) =>
{
var thisTextBlock = (TextBlock) o; // casting the sender as TextBlock
var rumID = int.Parse(thisTextBlock.Name); // since you bind the name of the text block to rumID
Edit(rumID); // this method where you can do the editting
}));
Upvotes: 0