2
WPF的DataGrid单元格内容我有一个WPF
DataGrid
。我想用户编辑后得到cell
值。该DataGrid
已填充了数据。用户可以编辑以前的数据。为了保存我想要的数据cell
来自event handler
的数据获取有关CurrentCellChanged
给我一个简单的代码来做到这一点。推荐一个event handler
。
WPF的DataGrid单元格内容我有一个WPF
DataGrid
。我想用户编辑后得到cell
值。该DataGrid
已填充了数据。用户可以编辑以前的数据。为了保存我想要的数据cell
来自event handler
的数据获取有关CurrentCellChanged
给我一个简单的代码来做到这一点。推荐一个event handler
。
只要用户编辑了单元格,就可以使用CellEditEnding事件来获取通知。
这个简单的程序说明了它:
XAML
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="500" Width="500">
<Grid>
<DataGrid x:Name="grid" CellEditEnding="cellEditEnding" />
</Grid>
</Window>
代码隐藏
public partial class MainWindow : Window
{
public class MyClass
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public string Prop3 { get; set; }
}
public MainWindow()
{
InitializeComponent();
var objects = new[]
{
new MyClass { Prop1 = "Object1", Prop2 = "Test1", Prop3 = "Hello" },
new MyClass { Prop1 = "Object2", Prop2 = "Test2", Prop3 = "Goodbye" },
new MyClass { Prop1 = "Object3", Prop2 = "Test3", Prop3 = "Welcome" }
};
grid.ItemsSource = objects;
}
private void cellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
//Only handles cases where the cell contains a TextBox
var editedTextbox = e.EditingElement as TextBox;
if (editedTextbox != null)
MessageBox.Show("Value after edit: " + editedTextbox.Text);
}
}
非常感谢彼得......它的伟大工程... – Kishor
虽然我认为下面有个很好的答案,你应该考虑使用WPF的内置数据绑定。它使得许多常见的数据任务更快更容易。 – Jasper