Silverlight搜索者

时间:2011-07-27 12:07:21

标签: .net silverlight null itemcontainergenerator listboxitems

我正在尝试做类似于Windows Phone 7中搜索者的操作,我所做的是以下内容,我有一个带有TextChanged事件的TextBox和一个HyperlinkBut​​tons列表框。我尝试的是这样的:

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++;
  }
}

这是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>

这里的问题是当我有68个或更多元素时,ContainerFromItem只返回null ListBoxItems ...

有什么想法吗?

谢谢大家

2 个答案:

答案 0 :(得分:0)

为什么不使用Color Data Binding?它应该是一种更简单的方式。

<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++;
  }
 }

答案 1 :(得分:0)

如果要点过滤列表框中的元素,请使用 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;
}

使用ItemContainer的问题是,只有在必须显示项目时才会创建它们,这就是为什么你有一个空值。