2011-07-27 45 views
0

我正在嘗試在Windows Phone 7中執行類似於搜索器的操作,並且我所做的是以下操作,我有一個帶有TextChanged事件的TextBox和一個HyperlinkBut​​tons的Listbox。我嘗試那就是:Silverlight搜索器

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 ...

有什麼想法?

謝謝大家

回答

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的問題是,它們被創建,只有當項目必須是顯示,這就是爲什麼你有一個空值。

+0

耶!那就是答案!謝謝! –

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

這很好,當有幾件物品,但它不是我正在尋找的效果,我想看到我的400名候選人列表減少到250,當我鍵入'a',例如 –