Monday 25 July 2011

CollectionViewSource and auto-completion

Jason Kemp has a good article on using the CollectionViewSource class of WPF to create an autocomplete implementation. The first part of the series is at this url.

This can be implemented in Powershell very easily to provide a means of searching and selecting from ComboBox's whose source is a list of PSObject's. The basic procedure:
  • Create a list as a New-Object system.collections.objectmodel.observablecollection[System.Object], and $obj.Add each new-object PSObject passing its -Property hashref.
  • Create a New-Object system.windows.data.collectionviewsource and set its source to the ObservableCollection.
  • Optionally create a number of New-Object system.componentmodel.sortdescription's and add them to the sortdescription collection of the CollectionViewModel's view.
  • Further on in your code, assign the CollectionViewModel's View as the ItemsSource of a ComboBox or other similar class, and add a TextChanged event to the corresponding textbox to refresh the view.
  • Finally, add a Filter to the View by casting a scriptblock as a [predicate[object]] with a single parameter which you can cast back to a psobject and perform your match against. You can find the related textbox by doing a FindName on the textbox's x:Name property, set in your form's XAML.