.netsilverlightnullitemcontainergeneratorlistboxitems

Silverlight searcher


I'm trying to do something similar to a searcher in Windows Phone 7, and what I've done is the following, I've got a TextBox with a TextChanged event and a Listbox of HyperlinkButtons. What I try it's this:

private void searchFriend_TextChanged(object sender, TextChangedEventArgs e)
{
  int index = 0;
  foreach (Person person in lbFriends.Items)
  {
    ListBoxItem lbi = lbFriends.ItemContainerGenerator.ContainerFromItem(index) as ListBoxItem;
    lbi.Visibility = Visibility.Visible;

    if (!person.fullName.Contains((sender as TextBox).Text))
    {
      lbi.Background = new SolidColorBrush(Colors.Black);
    }
    index++;
  }
}

And here is the xaml:

<TextBox x:Name="searchFriend" TextChanged="searchFriend_TextChanged" />
<ListBox x:Name="lbFriends" Height="535" Margin="0,0,0,20">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <StackPanel>
        <HyperlinkButton x:Name="{Binding id}" Content="{Binding fullName}" FontSize="24" Click="NavigateToFriend_Click" />
      </StackPanel>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

The problem here is when I've 68 or more elements, the ContainerFromItem just returns null ListBoxItems...

Any idea?

Thank you all


Solution

  • if the point is to filter the elements in the listbox then use a CollectionViewSource :

    System.Windows.Data.CollectionViewSource cvs;
    private void SetSource(IEnumerable<string> source)
    {
         cvs = new System.Windows.Data.CollectionViewSource();
         cvs.Source=source;
         listBox1.ItemsSource = cvs.View;
    }
    private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
         var box = (TextBox)sender;
         if (!string.IsNullOrEmpty(box.Text))
            cvs.View.Filter = o => ((string)o).Contains(box.Text);
         else
            cvs.View.Filter = null;
    }
    

    the problem using ItemContainer is that they are created only when the item has to be shown, that's why you have a null value.