Silverlight,将AutoCompleteBox.SelectedItem重置为null

时间:2010-06-23 07:02:33

标签: silverlight-4.0 autocompletebox

我遇到AutoCompleteBox问题。我想用它作为可编辑的组合框。所以我创建了继承自AutoCompletBox的自定义控件,并添加了两个名为SelectedValue(用于绑定到DataContext)和SelectedValuePath的依赖项属性。当用户选择一个项目时,我的自定义控件按以下方式更新SelectedValue:

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

有效。

相反,当基础datacontext发生变化时,SelectedValue也会发生变化;所以自定义控件的SelectedItem也必须改变:

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;
      }
   }
}

当SelectedValue为null时,让我感到困扰的是什么。即使SelectedItem设置为null,如果用户手动编辑了Text属性,也不会将其清除。所以SelectedItem = null但AutoCompleteBox显示手动输入的文本。有人能告诉我重置AutoCompleteBox.SelectedItem属性的正确方法吗?

3 个答案:

答案 0 :(得分:2)

多么巧合......今天我只是在做同样的事情。实际上甚至懒得设置SelectedItem = null。您可以设置Text = String.Empty,文本区域和SelectedItem都将被清除。

答案 1 :(得分:2)

在MVVM设置中不起作用

答案 2 :(得分:-1)

它解决了问题:

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

但它导致其他问题 - 当您选择项目,并插入信件......

相关问题