synergetic
synergetic

Reputation: 8026

Silverlight, resetting AutoCompleteBox.SelectedItem to null

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?

Upvotes: 2

Views: 1839

Answers (3)

yantrab
yantrab

Reputation: 1

It is solve the problem:

selectedChange += (e,v) => {if (selected item == null) Text = String.Empty};

but it couse to other problem - when you select item, and insert later...

Upvotes: -1

EzaBlade
EzaBlade

Reputation: 657

That doesn't work in an MVVM set up

Upvotes: 2

Josh
Josh

Reputation: 69262

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.

Upvotes: 2

Related Questions