【问题标题】:DataGrid CanUserAddRows = True数据网格 CanUserAddRows = True
【发布时间】:2012-08-15 21:22:48
【问题描述】:

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

  <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" />

【问题讨论】:

    标签: wpf xaml wpfdatagrid


    【解决方案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);
      }
    }
    

    【讨论】:

    • 在纯 XAML 中是否有任何替代方法?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-15
    相关资源
    最近更新 更多