WPF toolkit (from Codeplex) includes a nice control for auto-complete textboxes. It supports also objects as items, not just strings. So we have a concept of selected item. Items can be filtered by simple string comparison (using simple built-in string based filters) or by defining custom filter which can use multiple properties (or whatever you like) to filter items. All these support XAML bindings so it’s all fine.

This allows us to use list of complex items as items source and use different properties for filtering, displaying items in drop-down list and displaying selected item in text box. For example, say we need to select a person from autocomplete and display only person’s last name in text box. But when user chooses person from autocomplete dropdown she wants to see person’s full name (and maybe some other properties) also so she can distinguish between persons. And lets say user wants to search by person’s nicknames also (meaning that when filtering results, we need to check person’s nicknames also). Okay, so far all good. We define custom ItemFilter and create binding for SelectedItem property and when we make a choice we can access selected item.

Problem occurs when there are multiple items with same display values (in our case multiple persons with the same last name). This triggers some weird behaviors on autocomplete side. We can see different persons in drop-down, make a selection and SelectedItem updates accordingly. But when drop-down closes, it looses currently selected item and starts finding it again from the items source based on the text in the text box. Because we have multiple persons with same last name, it selects first one it finds. And selected item is not what user chose, anymore.

Seems it’s quite well known problem based on google, but I didn’t find any solution that I really like. So it was time to dig into the source code. My idea was to create a separate property for my selected item (I call it RealSelectedItem), which behaves similarly to original SelectedItem, so it has also it’s own change events and so forth and I can directly bind to this property. Only problem is to find a proper place to update this property, so I can control when it’s updated and when not.

After digging through source, I found an interesting peace – ISelectionAdapter, which seems to be responsible for selection in drop-down only, sounds like a good place to start. It had events for commiting and cancelling selection, so I can get notifications when selection is changed. I overrode GetSelectionAdapterPart() method (which creates and returns ISelectionAdapter) and attached my methods to Commit and Cancel events when I update my RealSelectedItem property based on the SelectedItem. Full source here:

public class MyAutoCompleteBox : AutoCompleteBox
{
	public object SelectedRealItem
	{
		get { return GetValue(SelectedRealItemProperty); }
		set { SetValue(SelectedRealItemProperty, value); }
	}

	public static readonly DependencyProperty SelectedRealItemProperty =
		DependencyProperty.Register(
			"SelectedRealItem",
			typeof(object),
			typeof(MyAutoCompleteBox),
			new PropertyMetadata(OnSelectedRealItemPropertyChanged));

	private static void OnSelectedRealItemPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
	{
		var source = d as MyAutoCompleteBox;
		source.SelectedItem = e.NewValue;
		if (e.NewValue == null)
		{
			source.Text = null;
		}

		var removed = new List<object>();
		if (e.OldValue != null)
		{
			removed.Add(e.OldValue);
		}

		var added = new List<object>();
		if (e.NewValue != null)
		{
			added.Add(e.NewValue);
		}

		source.OnRealSelectionChanged(new SelectionChangedEventArgs(SelectionChangedEvent, removed, added));
	}

	protected virtual void OnRealSelectionChanged(SelectionChangedEventArgs e)
	{
		RaiseEvent(e);
	}

	public static readonly RoutedEvent RealSelectionChangedEvent = EventManager.RegisterRoutedEvent("RealSelectionChanged", RoutingStrategy.Bubble, typeof(SelectionChangedEventHandler), typeof(MyAutoCompleteBox));

	public event SelectionChangedEventHandler RealSelectionChanged
	{
		add { AddHandler(RealSelectionChangedEvent, value); }
		remove { RemoveHandler(RealSelectionChangedEvent, value); }
	}

	protected override ISelectionAdapter GetSelectionAdapterPart()
	{
		var adapter = base.GetSelectionAdapterPart();
		adapter.Commit += (o, a) => UpdateSelectedValue(adapter.SelectedItem);
		adapter.Cancel += (o, a) => UpdateSelectedValue(null);
		return adapter;
	}

	private void UpdateSelectedValue(object value)
	{
		SelectedRealItem = value;
	}
}

Seems to work perfectly fine so far, with or without custom item template for drop down. Though, it doesn’t update RealSelectedItem when user navigates through items (like it is with SelectedItem), but I don’t need that anyway. I only want to know when user made up her mind and selection is made.

For Caliburn I needed to add my own element convention to use x:Name binding convention (actually it was already there, only for SelectedItem property), its basically one-liner (btw Caliburn doesn’t include convention for original SelectedItem either):

ConventionManager.AddElementConvention<AsyncAutoCompleteBox>(AsyncAutoCompleteBox.SelectedRealItemProperty, "SelectedRealItem", "RealSelectionChanged")
				.ApplyBinding = (viewModelType, path, property, element, convention) => ConventionManager.SetBinding(viewModelType, path, property, element, convention);
  • Twitter
  • Facebook
  • Technorati Favorites
  • Share/Bookmark