【问题标题】:Silverlight, resetting AutoCompleteBox.SelectedItem to nullSilverlight,将 AutoCompleteBox.SelectedItem 重置为 null
【发布时间】:2010-06-23 07:02:33
【问题描述】:

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

【问题讨论】:

标签: silverlight-4.0 autocompletebox


【解决方案1】:

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

【讨论】:

  • 谢谢乔希,你真的拯救了我的一天。
  • 很高兴听到这个消息。如果您找到使用 IsTextCompletionEnabled=True 的方法,请告诉我在您打开组合框时显示下拉列表中的所有项目。这就是今天让我跌落悬崖的原因。
  • 另外,真正帮助我理解 AutoCompleteBox 的各种属性以及它们在不同设置下的行为方式的一件事是在框旁边设置三个标签。一个绑定到 SelectedItem,一个绑定到 Text,一个绑定到 SearchText。看看值如何/何时在键入、从下拉列表中选择等时发生变化是很有趣的。
  • 我刚开始玩 AutoCompleteBox; 3 个标签是个好主意。我正在从 codeproject.com 学习 AutoCompleteComboBox (链接在我的评论中,就在问题下方)。该自定义控件在单击时显示所有项目,使用 ItemFilter 属性。也许有帮助。
【解决方案2】:

这在 MVVM 设置中不起作用

【讨论】:

  • 我面临同样的问题。如何让它在 MVVM 中工作?
【解决方案3】:

解决问题:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-27
    • 2021-01-25
    • 1970-01-01
    • 2016-01-13
    • 2017-02-24
    相关资源
    最近更新 更多