简体   繁体   English

DataGrid列模板中的按钮交互

[英]Button interaction in a DataGrid column template

In a C# WPF program I have a grid that I have successfully populated with my data. 在C#WPF程序中,我有一个已成功填充数据的网格。 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
}

Just bind the Id , or better yet the entire data object, as the CommandParameter 只需将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
}

This will also work if you decide to switch your application so it uses the MVVM design pattern. 如果您决定切换应用程序以使其使用MVVM设计模式,那么这也将起作用。 For example, the XAML would look like this: 例如,XAML如下所示:

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

What I understand is that you need to have the rumId of the clicked Text block in order to edit it. 据我了解,您需要具有单击的Text块的rumId才能进行编辑。

While setting the Click event you can do the following. 在设置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 
      })); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM