开发者

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

开发者 https://www.devze.com 2022-12-21 09:47 出处:网络
in wpf datagrid how to get the blank row on top? ie when user wants to add new row, it always comes at t开发者_JAVA百科he bottom. But I want it to be on top ... can i do this in XAML ?What about NewIt

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


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.


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


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());


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

精彩评论

暂无评论...
验证码 换一张
取 消