Ad

View Lost When Refreshing ObjectDataProvider

- 1 answer

I'm implementing a textbox filter on a list based on Josh Smith's example at http://joshsmithonwpf.wordpress.com/2007/06/12/searching-for-items-in-a-listbox. Basically, it sets the Filter on the view to a delegate that checks against the text in the search box. I hook up the filter like so:

var pickerView = FindResource("sortedRulesView") as CollectionViewSource;
new TextSearchFilter(pickerView.View, SearchTextBox);

Later, when I refresh the ObjectDataProvider, the filter is lost. I've noticed that pickerView.View has a different hashcode after the refresh. Are all the views recreated when the data refreshes? Does that mean I should reattach the filter again whenever I call ObjectDataProvider.Refresh()? Is there some smarter way to install this filter that wouldn't require babysitting?

Ad

Answer

You're right in saying that CollectionViewSource.View will be replaced when CollectionViewSource.Source is set.

The solution is to use the CollectionViewSource.Filter event instead of the CollectionView.Filter property. This will stick around when your View goes away.

You can do this with minimal changes to Josh Smith's TextSearchFilter class:

public class TextSearchFilter
{
    public TextSearchFilter( 
        CollectionViewSource filteredView, 
        TextBox textBox )
    {
        string filterText = "";

        filteredView.Filter += delegate( object obj, FilterEventArgs e )                
        {
            if( String.IsNullOrEmpty( filterText ) )
                e.Accepted = true;

            string str = e.Item as string;
            if( String.IsNullOrEmpty( str ) )
                e.Accepted = false;

            int index = str.IndexOf(
                filterText,
                0,
                StringComparison.InvariantCultureIgnoreCase );

            e.Accepted = index > -1;
        };          

        textBox.TextChanged += delegate
        {
            filterText = textBox.Text;
            filteredView.View.Refresh();
        };
    }
}

Your hookup code then becomes:

var pickerView = FindResource("sortedRulesView") as CollectionViewSource;
new TextSearchFilter(pickerView, SearchTextBox);
Ad
source: stackoverflow.com
Ad