Multithreaded WPF in the user interface

In my C # WPF application, I have one DataGrid, and right above it TextBox, so that the user can search and filter the grid as it is entered. If the user quickly picks up speed, the text will not be displayed until 2 seconds after they print, because the UI thread is too busy updating the grid.

Since most of the delay is all on the user interface side (i.e., filtering the data source is almost instantaneous, but restoring and re-rendering the grid is slow), multithreading did not help. Then I tried to set the dispatcher of that grid only to a lower level while the grid is being updated, but this also did not solve the problem. Here is some code ... Any suggestions on how to solve this problem?

string strSearchQuery = txtFindCompany.Text.Trim();

this.dgCompanies.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new Action(delegate
    {
        //filter data source, then
        dgCompanies.ItemsSource = oFilteredCompanies;
    }));
+4
source share
2 answers

If you target .net 4.5, you need to set the property Delayto TextBox, which will prevent the source value from being set until a certain time threshold is reached (until the user stops typing).

<TextBox Text="{Binding SearchText, Delay=1000}"/>

1 , .

/, .

+3

ListCollectionView ItemsSource , ItemsSource.

100000 , .

ViewModel

class ViewModel
    {
        private List<string> _collection = new List<string>(); 
        private string _searchTerm;

        public ListCollectionView ValuesView { get; set; }

        public string SearchTerm
        {
            get
            {
                return _searchTerm;
            }
            set
            {
                _searchTerm = value;
                ValuesView.Refresh();
            }
        }

        public ViewModel()
        {
            _collection.AddRange(Enumerable.Range(0, 100000).Select(p => Guid.NewGuid().ToString()));

            ValuesView = new ListCollectionView(_collection);
            ValuesView.Filter = o =>
                {
                    var listValue = (string)o;
                    return string.IsNullOrEmpty(_searchTerm) || listValue.Contains(_searchTerm);
                };
        }
    }

                   

<TextBox Grid.Row="0" Text="{Binding SearchTerm, UpdateSourceTrigger=PropertyChanged}" />

<ListBox ItemsSource="{Binding ValuesView}"
         Grid.Row="1" />

+4

Source: https://habr.com/ru/post/1531189/


All Articles