如何从TextChanged事件更新ListBox

时间:2014-05-18 15:01:46

标签: c# wpf

我有一个TextBox,我让用户输入一些文本,然后过滤一个ListBox(有点像自动完成)。但是,一旦在TextBox上触发TextChanged事件,我不确定如何更新ListBox?

查看

<TextBox Name="textBox" TextChanged="textBox_TextChanged"/>

<ListBox ItemsSource="{Binding NamesList}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

视图模型

public ObservableCollection<string> NamesList
{
    get
    {
        IEnumerable<string> names = MethodCallToGetStrings();
        return new ObservableCollection<string>(names);
    }
}

public void UpdateNamesList(string _searchTerm)
{
    IEnumerable<string> names = MethodCallToGetStrings()
        .Where(x => x.Name.Contains(_searchTerm))
        .Select(x => x.Name);

    // how to update NamesList from here?
}

TextBox活动

private void textBox_TextChanged(object sender, TextChangedEventArgs e)
{
    TextBox textBox = sender as TextBox;
    m_viewModel.UpdateNamesList(textBox.Text);
}

1 个答案:

答案 0 :(得分:2)

public void UpdateNamesList(string _searchTerm)
{
    IEnumerable<string> names = MethodCallToGetStrings()
        .Where(x => x.Name.Contains(_searchTerm))
        .Select(x => x.Name);

    NamesList.Clear();
    foreach(name in names) 
    {
       NamesList.Add(name);
    }
}