更改单元格绑定值并更新Datagrid

时间:2018-08-16 16:53:47

标签: c# wpf datagrid

我想更改特定行的单元格绑定值的值。我已将值与Name和Code属性绑定在一起。假设第一行被选中。在CurruntCellChange事件上,我想在该特定行中将Name属性的值更改为“ 1”。我已经编写了将代码更改为((Item)Datagrid.Items[rowIndex]).Name = "1";的代码,但更改未反映出来。

<DataGrid  DataGridCell.Selected="DataGrid_GotFocus" SelectionUnit="Cell" 
                   SelectionMode="Single" Name="Datagrid"  AutoGenerateColumns="False" 
                   PreviewKeyDown="Datagrid_PreviewKeyDown" 
                   CurrentCellChanged="Datagrid_CurrentCellChanged" SelectionChanged="Datagrid_SelectionChanged" SelectedCellsChanged="Datagrid_SelectedCellsChanged">

            <DataGrid.Columns>

                <DataGridTextColumn Header="Code" Width="1*" Binding="{Binding Code, Mode=TwoWay}"/>
                <DataGridTextColumn Header="Name" Width="1*" Binding="{Binding Name, Mode=TwoWay}"/>
            </DataGrid.Columns>
        </DataGrid>

事件:

private void Datagrid_CurrentCellChanged(object sender, EventArgs e)
        {
            Datagrid.BeginEdit();
            if (Datagrid.SelectedCells.Count > 0)
            {
                DataGridCellInfo cell = Datagrid.SelectedCells[0];

                var generator = Datagrid.ItemContainerGenerator;
                int columnIndex = cell.Column.DisplayIndex;
                int rowIndex = generator.IndexFromContainer(generator.ContainerFromItem(cell.Item));
 ((Item)Datagrid.Items[rowIndex]).Name = "1";
}

名称属性:

namespace Inventory_Control.Classes
{
    class Item
    {
        public string Id { get; set; }
        public string Code { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public string Quantity { get; set; }
        public string UnitPrice { get; set; }
        public string SubTotal { get; set; }
        public string Category { get; set; }
        public string Type { get; set; }
        public string Location { get; set; }
    }
}

1 个答案:

答案 0 :(得分:1)

您需要在您的Item类中实现INotifyPropertyChanged 然后在您的

public string Name { get; set; }

设置时,您需要引发“属性更改”事件

要实现INotifyPropertyChanged,您需要在您的课程中实现此接口,以下是最简单的实现方法

public event PropertyChangedEventHandler;

private void NotifyPropertyChanged(String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

,然后您的Name属性看起来像

private string name;

public string Name
    {
        get { return name; }
        set
        {
            name = value;
            NotifyPropertyChanged("Name");
        }
    }