DataGrid CanUserAddRows = True

时间:2012-08-15 21:22:48

标签: wpf xaml wpfdatagrid

我有一个wpf数据网格,其设置CanUserAddRows设置为true。这将向数据网格添加一个空白空行,当用户双击该行时,它将清零所有属性并将其添加到collection / itemsource(ObservableCollection)。问题是当空行为零并将其添加到集合时,我需要添加另一个空白行,并在添加之前立即使用该行并将其清零。相反,在我选择新行(selectionchange)之前,新的空行不会显示在数据网格上。希望这清楚我要求的是什么。关于如何解决这个问题的任何想法?任何输入的Thx。

  <DataGrid Grid.Row="1" RowHeaderWidth="0" BorderBrush="Black" ItemsSource="{Binding MyCollection, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" SelectedItem="{Binding SelectedRow, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" Height="280" Focusable="True" CanUserAddRows="True">

       <DataGridTextColumn Binding="{Binding Weight}" Header="Tare Lbs." Width="70" />
       <DataGridTextColumn Binding="{Binding Bu, UpdateSourceTrigger=PropertyChanged}" Header="Gross Bu." Width="70" />

1 个答案:

答案 0 :(得分:1)

如果调用DataGrid.CommitEdit(),它将完成添加新行并为您创建新的空行。我们在DataGrid.CurrentCellChanged()。

中完成

XAML

<DataGrid x:Name="theGrid" ItemsSource="{Binding MyCollection, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" SelectedItem="{Binding SelectedRow, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" CanUserAddRows="True" CurrentCellChanged="theGrid_CurrentCellChanged">

代码背后:

private void theGrid_CurrentCellChanged(object sender, EventArgs e)
{
   DataGrid grid = sender as DataGrid;

   IEditableCollectionView items = (IEditableCollectionView)grid.Items;
   if (items != null && items.IsAddingNew) {
      // Commit the new row as soon as the user starts editing it
      // so we get a new placeholder row right away.
      grid.CommitEdit(DataGridEditingUnit.Row, false);
  }
}