xSillusx xSillusx - 1 year ago 104
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download