tags:

views:

216

answers:

4

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 ?

A: 

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());
Randolpho
Ooh nice .. thas one way .. but thats simulating the add row effect ... you have to wrote event handlers and manage everything ... i can do that and thank you for the tip.i am using .net 3.5 datagrid .. i think its betaand i doing it exactly the way u have mentioned .... any other ideas?
kedar
The DataGrid is available for .NET 3.5 if you install the WPF Toolkit, available on codeplex.
Dave
A: 

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.

Alex_P
A: 

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

Johan Zell
+2  A: 

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.

woodyiii
Excellent answer woodyiii (+1). I added some code and a note about the NET Framework version to make your answer even beter.
Ray Burns