我遇到了AutoCompleteBox的問題。我想用它作爲可編輯的組合框。所以我創建了從AutoCompletBox繼承的自定義控件,並添加了兩個名爲SelectedValue(用於綁定到DataContext)和SelectedValuePath的依賴項屬性。當用戶選擇一個項目時,我的自定義控件按以下方式更新SelectedValue:Silverlight,將AutoCompleteBox.SelectedItem重置爲null
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爲null時。即使SelectedItem設置爲null,如果用戶手動編輯它,Text屬性也不會被清除。因此SelectedItem = null,但AutoCompleteBox顯示手動輸入的文本。有人可以讓我看到重置AutoCompleteBox.SelectedItem屬性的正確方法嗎?
其實,上面的代碼是從AutoCompleteComboBox;見: http://www.codeproject.com/KB/silverlight/AutoComplete_ComboBox.aspx – synergetic 2010-06-23 07:06:24