0

我正在尝试做类似于 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 ...

任何的想法?

谢谢你们

4

2 回答 2

0

为什么不使用颜色数据绑定?它应该是一种更简单的方法。

<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++;
  }
 }
于 2011-07-27T14:05:18.663 回答
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 的问题是它们仅在必须显示项目时创建,这就是为什么您有一个空值。

于 2011-07-27T15:43:16.633 回答