DataGrid列模板中的按钮交互

时间:2012-02-17 18:48:41

标签: c# wpf datagrid buttonclick

在C#WPF程序中,我有一个网格,我已成功填充了我的数据。一列有一个我想链接到编辑页面的按钮。代码如下。

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);

代码成功运行,每次选择按钮时都会出现一个消息框。

如何让它调用另一个方法,然后从中检索我选择的按钮的行号?

后续方法看起来像,我怎么称呼它?

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
}

2 个答案:

答案 0 :(得分:1)

只需将Id或更好的整个数据对象绑定为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
}

如果您决定切换应用程序以使其使用MVVM设计模式,这也将起作用。例如,XAML看起来像这样:

<Button Command="{Binding EditCommand}"
        CommandParameter="{Binding }" />

答案 1 :(得分:0)

我的理解是您需要拥有所单击的文本块的rumId才能进行编辑。

设置Click事件时,您可以执行以下操作。

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 
      }));