DataGrid列模板中的按钮交互
在C#WPF程序中,我有一个已成功填充数据的网格。一列有一个我想链接到编辑页面的按钮。代码如下。DataGrid列模板中的按钮交互
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
}
只需绑定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 }" />
它不会像调用ButtonClick那样困难。 – 2012-02-17 19:34:34
@RogerStark只需更改设置'Click'事件的代码行,使其指向您的方法而不是定义内联:'textBlockFactory.AddHandler(Button.ClickEvent,ButtonClick);' – Rachel 2012-02-17 19:38:27
感谢,迄今为止工作,现在我需要提取id + \t \t发件人\t {System.Windows.Controls.Button:5} \t object {System.Windows.Controls.Button}我想提取'5' – 2012-02-17 20:09:09
我明白了什么是你需要有点击的文本块的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
}));
我宁愿用其他的控制比DataGrid中才能有更大的灵活性。我做了一些使用行列和按钮的ListBox,数据模板和一点代码隐藏功能。如果你愿意,我可以给你一些例子 – Gab 2012-02-17 18:55:46