in wpf datagrid how to get the blank row on top?

前端 未结 4 1720
隐瞒了意图╮
隐瞒了意图╮ 2020-12-16 06:32

in wpf datagrid how to get the blank row on top? ie when user wants to add new row, it always comes at the bottom. But I want it to be on top ... can i do this in XAML ?

相关标签:
4条回答
  • 2020-12-16 06:44

    You would have to write your own template for DataGrid where you would place the NewItemPlaceholder part on top of the grid. Look at this example to start with (though the example is not the answer it'll point you in the right direction).

    On the side note may I ask why would you need to have NewItemPlaceholder at the top? It kind of breaks the natural top to bottom flow we're so used to see when dealing with lists/grids.
    It may well be more intuitive to have New Item thing at the bottom and Insert Item option in context menu for the grid or something along these lines. That is only my opinion of course.

    0 讨论(0)
  • 2020-12-16 06:47

    This answer depends greatly on how you are binding your DataGrid, specifically what the underlying type of your ItemsSource is. This answer assumes you are using an ObservableCollection. Since you mention WPF specifically, I also assume you mean .NET 4.0, since the DataGrid is only available in Silverlight 3 and .NET 4.0.

    I assume that you are newing up a row by calling

    ItemSource.Add(new MyObject());
    

    To get the behavior you desire, use the following instead:

    ItemSource.Insert(0, new MyObject());
    
    0 讨论(0)
  • 2020-12-16 06:53

    If you're using an MMVM approach, you can add a new row programatically like:

            var newEmp = new EmployeeViewModel(new EmployeeDto());
            EmployeeList.Add(newEmp);
            EmployeeList.Move(EmployeeList.IndexOf(newEmp), 0);
    

    In my example i am using an EmployeeListViewModel to display an ObservableCollection of EmployeeViewModels.

    Then you are also able to write tests for this behaviour. More control than in XAML....

    /Johan

    0 讨论(0)
  • 2020-12-16 06:58

    What about NewItemPlaceholderPosition.AtBeginning? I don't have a code example but that seems to be what you're describing. You could always do what Johan is suggesting and Move or Sort the items in the grid programmatically.

    Code example added by Ray Burns:

    var view = CollectionView.GetDefaultCollectionView(EmployeeList)
                 as IEditableCollectionView;
    if(view!=null)
      view.NewItemPlaceholderPosition = NewItemPlaceholderPosition.AtBeginning;
    

    Note that this requires NET Framework 3.5 or above.

    0 讨论(0)
提交回复
热议问题