views:

414

answers:

1

We have a WPF app that has a DataGrid inside a ListView.

private DataTable table_;

We do a bunch or dynamic column generation ( depending on the report we are showing )

We then do the a query and fill the DataTable row by row, this query may or may not have data.( not the problem, an empty grid is expected ) We set the ListView's ItemsSource to the DefaultView of the DataTable.

lv.ItemsSource = table_.DefaultView;

We then (looking at the user's pass usage of the app, set the sort on the column) Sort Method below:

private void Sort(string sortBy, ListSortDirection direction)
{
 ICollectionView dataView = CollectionViewSource.GetDefaultView(lv.ItemsSource);

 dataView.SortDescriptions.Clear();

 var sd = new SortDescription(sortBy, direction);

 dataView.SortDescriptions.Add(sd);

 dataView.Refresh();
}

In the Zero DataTable rows scenario, the sort does not "hold"? and if we dynamically add rows they will not be in sorted order.

If the DataTable has at-least 1 row when the sort is applied, and we dynamically add rows to the DataTable, the rows com in sorted correctly.

I have built a standalone app that replicate this...

It is an annoyance and I can add a check to see if the DataTable was empty, and re-apply the sort...

Anyone know whats going on here, and am I doing something wrong?

FYI: What we based this off if comes from the MSDN as well: http://msdn.microsoft.com/en-us/library/ms745786.aspx

Update:

the sort not "holding" means, the ICollectionView.SortDescriptions has a SortDescription, but is not sorting the data as its added, again only happens if there is no rows in the underlying DataTable if there are rows when the SortDescription is added, then everything works out fine~

+1  A: 

Clearly this is a GUI bug. It would be nice to work around it on the GUI level not on the data level. Here is one suggestion.

DataTable table_ = new DataSet1().DataTable1;
ICollectionView dv_;

public MainWindow()
{
    InitializeComponent();

    dv_ = CollectionViewSource.GetDefaultView(table_);
    dv_.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(dv_CollectionChanged);

    lv.ItemsSource = dv_;
}
void dv_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{

    if (e.Action == NotifyCollectionChangedAction.Add && table_.Rows.Count == 1 )
        dv_.Refresh();
}
jyoung