简体   繁体   中英

Dynamically update a data bound listbox C# WPF

So despite finding articles online I still cannot figure this out.

I have a Listbox

<ListBox HorizontalAlignment="Left" Margin="54,35,0,0" Name="resultsbox" VerticalAlignment="Top" Width="382" Visibility="Collapsed">
    <DataTemplate>
        <StackPanel>
            <TextBlock Text="{Binding nameElement}"/>
        </StackPanel>
    </DataTemplate>
</ListBox>

That is databound to

   ObservableCollection<string> results = new ObservableCollection<string>();

and is updated with

   private void searchbox_TextChanged(object sender, TextChangedEventArgs e)
    {

    resultsbox.Visibility = Visibility.Visible;

    resultsbox.ItemsSource = results;



    if (results.Count == 0)
    {
        foreach (ele item in eles)
        {
            if (!results.Contains(item.nameElement))
            {
                results.Add(item.nameElement);
            }
        }
    }
    else
    {
        resultsbox.Items.Clear();
    }

    if (searchbox.Text.Equals(""))
    {
        window1.Height = 47;
        resultsbox.Visibility = Visibility.Collapsed;
    }


    if (resultsbox.Items.Count == 0)
    {
        resultsbox.Visibility = Visibility.Collapsed;
        window1.Height = 47;
    }
    else{
        window1.Height = 47 + (22 * resultsbox.Items.Count);
    }
  }

It loads ALL the data in there but WILL NOT UPDATE!

If I do resultsbox.clear() it says you can't clear bound items. If you try and clear the source it does nothing. If you try and set the resultsbox itemsource to null and clear the source then rebind it, nothing. If you try and bind the listbox to an empty source it does nothing....

The answer was changing the foreach loop in the update from

 resultsbox.ItemsSource = results;
    if (results.Count == 0)
    {
        foreach (ele item in eles)
        {
            if (!results.Contains(item.nameElement))
            {
                results.Add(item.nameElement);
            }
        }
    }

to

results.Clear();
    foreach (ele item in eles)
    {
        if (item.nameElement.ToLower().Contains(searchbox.Text.ToLower()))
        {
            results.Add(item.nameElement);
        }
    }

resultsbox.ItemsSource = results;

You can try using Two-Way Mode Binding to achieve your requirement IMO,

<ListBox HorizontalAlignment="Left" Margin="54,35,0,0" Name="resultsbox" VerticalAlignment="Top" Width="382" Visibility="Collapsed">
<DataTemplate>
    <StackPanel>
        <TextBlock Text="{Binding nameElement, Mode=TwoWay}"/>
    </StackPanel>
</DataTemplate>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM