更改了单元格上的WPF DataGrid源更新

Kha*_*led 20 wpf datagrid wpfdatagrid

我是WPF的新手,我用它来建立一个销售点系统.

我有一个DataGrid绑定到一个主窗口控制ObservableCollectionItem,将要出售的收银员将进入/扫描项目每个项目的默认数量为1,但它是可用于收银员手动更改数量.

每当我更改数量时,它应该在我将单元格离开单元格到行中的另一个单元格时使用项目价格的总和更新总价格,但是不会发生,只有当我转到另一行时才更新源不是同一行中的另一个单元格.

无论如何在DataGrid更改单元格而不是行时强制更新源?

Alm*_*und 59

应用于UpdateSourceTrigger=LostFocus每个绑定.它对我来说就像一个魅力.

<DataGridTextColumn Header="Name" Binding="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" />
Run Code Online (Sandbox Code Playgroud)

  • 大!此外,UpdateSourceTrigger = PropertyChanged在更改单元格后立即工作. (5认同)

mat*_*nja 9

接受的答案中的代码对我不起作用,因为从ItemContainerGenerator.ContainerFromItem(item)结果中获取的行为null并且循环非常慢.

这个问题的一个更简单的解决方案是这里提供的代码:http: //codefluff.blogspot.de/2010/05/commiting-bound-cell-changes.html

private bool isManualEditCommit;
private void HandleMainDataGridCellEditEnding(
  object sender, DataGridCellEditEndingEventArgs e) 
{
 if (!isManualEditCommit) 
 {
  isManualEditCommit = true;
  DataGrid grid = (DataGrid)sender;
  grid.CommitEdit(DataGridEditingUnit.Row, true);
  isManualEditCommit = false;
 }
}
Run Code Online (Sandbox Code Playgroud)


gra*_*tnz 4

是的,这是可能的。您的问题与 DataGrid 基本相同- 更改编辑行为

下面的代码主要来自 Quartermeister 的答案,但我添加了一个BoundCellLevel,当您需要在当前单元格更改时更新绑定DependencyProperty时,您可以设置它。DataGrid

public class DataGridEx : DataGrid
{
    public DataGridEx()
    {

    }

    public bool BoundCellLevel
    {
        get { return (bool)GetValue(BoundCellLevelProperty); }
        set { SetValue(BoundCellLevelProperty, value); }
    }

    public static readonly DependencyProperty BoundCellLevelProperty =
        DependencyProperty.Register("BoundCellLevel", typeof(bool), typeof(DataGridEx), new UIPropertyMetadata(false));

    protected override Size MeasureOverride(Size availableSize)
    {
        var desiredSize = base.MeasureOverride(availableSize);
        if ( BoundCellLevel )
            ClearBindingGroup();
        return desiredSize;
    }

    private void ClearBindingGroup()
    {
        // Clear ItemBindingGroup so it isn't applied to new rows
        ItemBindingGroup = null;
        // Clear BindingGroup on already created rows
        foreach (var item in Items)
        {
            var row = ItemContainerGenerator.ContainerFromItem(item) as FrameworkElement;
            row.BindingGroup = null;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)