我有一个 WPF
的 DataGrid
。我想要在用户编辑后获取单元格的值。这个 DataGrid
已经填充了数据,用户可以编辑之前的数据。为了保存数据,我希望从一个 事件处理程序
中获取单元格数据。
请给我一个简单的代码来实现它。建议使用一个 事件处理程序
。
您可以使用 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);
}
}