我对 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 属性的正确方法吗?