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?