2

我对 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;

有用。

相反,当底层数据上下文发生变化时,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 为空时。即使 SelectedItem 设置为 null,如果 Text 属性是由用户手动编辑的,它也不会被清除。所以 SelectedItem = null 但 AutoCompleteBox 显示手动输入的文本。有人可以告诉我重置 AutoCompleteBox.SelectedItem 属性的正确方法吗?

4

3 回答 3

2

这在 MVVM 设置中不起作用

于 2011-01-28T11:54:26.410 回答
2

真是巧合……我今天只是在做同样的事情。事实上,甚至不必费心设置 SelectedItem = null。您可以只设置 Text = String.Empty 并且文本区域和 SelectedItem 都将被清除。

于 2010-06-23T07:07:41.633 回答
-1

这是解决问题:

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

但这会导致其他问题-当您选择项目并稍后插入时...

于 2013-09-09T10:17:32.220 回答