views:

20

answers:

1

I have a problem with AutoCompleteBox. I wanted to use it as editable combobox. So I created custom control inheriting from AutoCompletBox and added two dependency properties named as SelectedValue (for binding to DataContext) and SelectedValuePath. When user selects an item, my custom control updates SelectedValue as the following way:

string propertyPath = this.SelectedValuePath;
PropertyInfo propertyInfo = this.SelectedItem.GetType().GetProperty(propertyPath);
object propertyValue = propertyInfo.GetValue(this.SelectedItem, null);
this.SelectedValue = propertyValue;

It works.

Reversely, when underlying datacontext changed, SelectedValue is also changed; so custom control's SelectedItem also has to change:

if (this.SelectedValue == null)
{
   this.SelectedItem = null; //Here's the problem!!!
}
else
{
   object selectedValue = this.SelectedValue;
   string propertyPath = this.SelectedValuePath;
   if (selectedValue != null && !(string.IsNullOrEmpty(propertyPath)))
   {
      foreach (object item in this.ItemsSource)
      {
         PropertyInfo propertyInfo = item.GetType().GetProperty(propertyPath);
         if (propertyInfo.GetValue(item, null).Equals(selectedValue))
            this.SelectedItem = item;
      }
   }
}

What troubles me is when SelectedValue is null. Even if SelectedItem is set to null, Text property is not cleared, if it was manually edited by user. So SelectedItem = null but AutoCompleteBox displays a text entered manually. Can someone show me right way of resetting AutoCompleteBox.SelectedItem property?

A: 

What a coincidence... I was just doing the same thing today. In fact don't even bother to set SelectedItem = null. You can just set Text = String.Empty and both the text area and the SelectedItem will be cleared.

Josh Einstein
Thank you Josh, you really saved my day.
synergetic
Glad to hear it. Let me know if you find a way to use IsTextCompletionEnabled=True *and* show all the items in the drop down list when you open the combo box. That's what drove me off a cliff today.
Josh Einstein
Also, one thing that really helped me wrap my head around the various properties of AutoCompleteBox and how they behave under different settings was to set up three labels next to the box. Bind one to SelectedItem, one to Text, and one to SearchText. It's interesting to see how/when the values change while typing, picking from a drop down, etc.
Josh Einstein
I just started playing with AutoCompleteBox; 3 labels are great idea. I was learning AutoCompleteComboBox from codeproject.com (the link is in my comment just under the question). That custom control shows all items when clicked, using ItemFilter property. Maybe it helps.
synergetic