在 CurrentCellChanged 上获取 WPF DataGrid 的单元格内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13069845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 05:56:45  来源:igfitidea点击:

Get cell content of WPF DataGrid on CurrentCellChanged

c#wpfdatagrid

提问by Kishor

I have a WPFDataGrid. I want to get the cellvalue after user edits it. The DataGridis already populated with data. User can edit previous data. To save data i want to get celldata from a event handler

我有一个WPFDataGrid. 我想cell在用户编辑后获取该值。在DataGrid已填充了数据。用户可以编辑以前的数据。为了保存数据,我想cellevent handler

Give me a simple code to do it. Suggest one event handler.

给我一个简单的代码来做到这一点。建议一event handler

回答by Peter Hansen

You can use the CellEditEnding event to get notified whenever a user has edited a cell.

您可以使用 CellEditEnding 事件在用户编辑单元格时收到通知。

This simple program illustrates it:

这个简单的程序说明了它:

XAML

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>

Code-behind

代码隐藏

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