开发者

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, Tex开发者_开发技巧tChangedEventArgs 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


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.


Why don't you use Color Data Binding? It should be a simpler way.

<HyperlinkButton x:Name="{Binding id}" Content="{Binding fullName}" Background="{Binding BackgroundColor}" FontSize="24"    Click="NavigateToFriend_Click" />


private SolidColorBrush _backgroundColor;

public SolidColorBrush BackgroundColor{
    get {

        return _backgroundColor;
    }
    set { _backgroundColor= value; }
}

private void searchFriend_TextChanged(object sender, TextChangedEventArgs e)
{
 int index = 0;
 foreach (Person person in lbFriends.Items)
 {
   if (!person.fullName.Contains((sender as TextBox).Text))
   {
     person.BackgroundColor= new SolidColorBrush(Colors.Black);
   }
   index++;
  }
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜