views:

158

answers:

2

I'm just getting started with collections (ObservableCollections) and I've hit a wall that I assumed would be easy. I'm sure it is easy but I'm just not finding the answer.

I have a WPF screen with a DataGrid to the left and TextBoxes to the right of the screen. The DataGrid is bound to the ObservableCollection (Activities) and I can click up and down the DataGrid and see my TextBoxes refresh with the correct info. I can then alter the info in the TextBoxes and save it back to the DB. All works perfectly!

However, when it comes to Adding a record to the collection I'm lost as to the correct approach. I'm using the Add method as shown below, but how do I move to this newly created record so it can be edited? I've tried a dozen approaches but I've yet to find a correct approach. The TextBoxes just remain focussed on the last edited record. Any ideas?

Private Activities As ObservableCollection(Of ActivityRecord)

Private Sub AddMode()
    Dim _ActivityRecord As New ActivityRecord(0, DateTime.Now, Nothing, "", gWorkerID, "")
    Activities.Add(_ActivityRecord)
'Code to move to the newly created record should go here
A: 

Hi,

In WPF, every ItemsControl derived control (list your DataGrid) secretly uses a derivative of CollectionView to facilitate the navigation between records/items - in effect it is the class which provides the currency mechanism that help other controls (like the textbox) determine which data bound item is current.

If you create a new object and add it to your ObservableCollection, you can use one of the CollectionView's MoveXXX methods to move to make that item current. You can (depending on what sort of CollectionView you get) also call the Add method on the CollectionView, and it will automatically call the Add method on your underlying ObservableCollection.

Either way, retriving a reference to the CollectionView is the secret. You can either use the CollectionView's static method (I forget it's name) to retrieve the view being used for your DataGrid, or (and this is my preferred method) you can explicitely create a ListCollectionView and bind your DataGrid to it, instead of the ObservableCollection.

Mark
Hi Mark, I'm using an Xceed datagrid which uses a DataGridCollectionView that does the same as ListCollectionView so I've decided to use that. Thanks for pointing me in the right direction. Mitch
Mitch
A: 

Is it ok to bind ListCollectionView to Xceed datagrid DataGridCollectionViewSource... I am able bind with observablecollection but not with listcollection View bith are dependency properties...Please help me

first time exceed