在AutoCompleteBox中我选择“AAAA”女巫是我人物收藏中第一个人的名字。 之后我按下将第一个人的名字改为“Jeniffer”的按钮。 代码工作正常,但AutocompleteBox选中的项目似乎没有刷新。
如何在更改名称后刷新所选项目?
XAML:
<Grid Background="LightBlue" >
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Controls:AutoCompleteBox x:Name="autoCompleteBox" Populating="autoCompleteBox_Populating" Height="30">
</Controls:AutoCompleteBox>
<Button Grid.Row="1" Click="Button_Click">Change first person Name</Button>
</Grid>
代码隐藏:
public partial class Window1 : Window {
public delegate void SearchResults(IEnumerable results);
public ObservableCollection<Person> Persons { get; set; }
public Window1() {
Persons = new ObservableCollection<Person> {
new Person {Name = "AAAA"},
new Person {Name = "BBBB"},
new Person {Name = "CCCC"},
};
InitializeComponent();
}
private void autoCompleteBox_Populating(object sender, PopulatingEventArgs e) {
e.Cancel = true;
Search(autoCompleteBox.SearchText, delegate(IEnumerable results) {
autoCompleteBox.ItemsSource = results;
autoCompleteBox.PopulateComplete();
});
}
private void Search(string phrase, SearchResults resultsDelegate) {
var results = new ObservableCollection<Person>();
foreach (var person in Persons) {
if (person.Name.ToLower().Contains(phrase.ToLower())) {
results.Add(person);
}
}
resultsDelegate(results);
}
private void Button_Click(object sender, RoutedEventArgs e) {
Persons.FirstOrDefault(p => p.Name == "Aaaaa").Name = "Jennifer";
}
}
public class Person {
public string Name { get; set; }
public override string ToString() {
return Name;
}
}
答案 0 :(得分:0)
最简单的方法是更改Text属性:
private void Button_Click(object sender, RoutedEventArgs e)
{
Persons.FirstOrDefault(p => p.Name == "AAAA").Name = "Jennifer";
if(autoCompleteBox.Text == "AAAA")
autoCompleteBox.Text = "Jennifer";
}
因为文本字段与SelectedItem属性无关,所以它只与Text属性连接。