2010-06-23 13 views
2

我遇到了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屬性的正確方法嗎?

+0

其實,上面的代碼是從AutoCompleteComboBox;見: http://www.codeproject.com/KB/silverlight/AutoComplete_ComboBox.aspx – synergetic 2010-06-23 07:06:24

回答

2

真是巧合......今天我只是在做同樣的事情。實際上甚至不用費心去設置SelectedItem = null。您只需設置Text = String.Empty,文本區域和SelectedItem就會被清除。

+0

謝謝喬希,你真的救了我的一天。 – synergetic 2010-06-23 07:29:41

+0

很高興聽到它。讓我知道如果您找到一種方法來使用IsTextCompletionEnabled = True *和*在打開組合框時顯示下拉列表中的所有項目。這就是今天驅車離開懸崖。 – Josh 2010-06-23 07:35:35

+0

此外,有一件事真的幫助我將自己的頭圍繞AutoCompleteBox的各種屬性以及它們在不同設置下的行爲如何在框旁邊設置三個標籤。將一個綁定到SelectedItem,一個綁定到Text,另一個綁定到SearchText。有趣的是,看看在輸入時如何/何時改變值,從下拉選擇等。 – Josh 2010-06-23 07:37:09

2

這不成立

+0

我面臨同樣的問題。如何使它在MVVM中工作? – 2015-04-10 23:33:27

-1

這是解決問題的一個MVVM工作:

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

但病程到另一個問題 - 當你選擇的項目,後來插...