2011-02-17 167 views
18

我是WPF的新手,我使用它來構建銷售點系統。WPF DataGrid源更新單元格更改

我有綁定到ItemObservableCollection主窗口,收銀員將進入/掃描項DataGrid控制出售每個項目的默認數量爲1,但它是可用於收銀員更改數量手動。

每當我改變數量時,它應該更新總價格與項目的價格之和,當我離開細胞到行上的另一個細胞時,但它不會發生,只有當我更新來源時轉到另一行而不是同一行中的另一個單元格。

有沒有辦法強制DataGrid更新單元格更改時的源而不是行?

回答

3

是的,這是可能的。你的問題是基本相同DataGrid - change edit behaviour

下面的代碼大部分來自Quartermeister的答案,但我添加了一個DependencyProperty BoundCellLevel可以設置當你需要一個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; 
     } 
    } 
} 
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; 
} 
} 
49

應用UpdateSourceTrigger=LostFocus到每個綁定。它對我來說就像一個魅力。

<DataGridTextColumn Header="Name" Binding="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" /> 
+0

+1更好地解決問題。其他單元格值應在單元上焦點丟失後立即更新,而不是焦點在行上丟失(默認)。 – retanik 2013-08-16 14:01:55

1

Almund是對的。 UpdateSourceTrigger=LostFocus將在您的情況下效果最好。正如你所提到的,當你移動到下一行時你的源代碼正在更新,這意味着我猜你正在使用ObservableCollection<T>來綁定你的DataGridItemSource。因爲那是你需要達到你想要的。

<DataGridTextColumn Header="Quantity" Binding="{Binding Quantity, 
        Mode=TwoWay, UpdateSourceTrigger=LostFocus}" /> 
<DataGridTextColumn Header="Total Price" Binding="{Binding TotalPrice, 
        Mode=TwoWay, UpdateSourceTrigger=LostFocus}" /> 

您需要將"UpdateSourceTrigger=LostFocus"添加到每個列中。

相關問題