xSillusx xSillusx - 1 month ago 9x
C# Question

C# wpf binding poblem - DataContext doesnt work as thought

Iam working on a program that can read XML files and will list
the information in a dataGrid.

It works like this:

I have a class : ListViewModel which contains the
data for the dataGrid in which format it can be displayed.

Then I got a Timer which will fire an event every second
to search for new lines in the XML file.

and at the end, i got a filter method which will filter the
information from the XML file before it will display on the dataGrid.

The thing is that I had a version where I used dataGrid.ItemsSource = filteredList;

But it bothered me that it flickered when a new items was added to the list.

So i heard about binding and the dataContext, maybe someone can explain
the correct use of Binding with DataContext?

I searched a while for what I was looking but i didnt found
an answer/explaination for me.


I think what you're after is a ListCollectionView - it's created off your list and that's what you bind to in the UI. And you then add filtering (or sorting) to it. Also useful for tracking changes to the current selection.

// create your list - this is where you add data
var rawList = new ObservableCollection<SomeStuff>();

// get a view into your list - thisis what you bind to in the UI
var publicViewThatYouBindTo = (ListCollectionView)CollectionViewSource.GetDefaultView(rawList);

// and now you can filter on that
publicViewThatYouBindTo.Filter = (o) =>
   return ((SomeStuff)o).SomeLogicToFilterBy(); 

Then you would do dataGrid.ItemSource = publicViewThatYouBindTo.