我正在使用 CollectionViewSource 过滤列表框中显示的记录。xaml 如下。
<Window x:Class="WPFStarter.ListBoxItemsFilter.ListBoxFilterUsingCollectionViewSource"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="userControl"
Title="ListBoxFilterUsingCollectionViewSource" Height="300" Width="300">
<Window.Resources>
<CollectionViewSource Source="{Binding ElementName=userControl, Path=DataContext.Items}"
x:Key="cvs" Filter="CollectionViewSource_Filter"/>
</Window.Resources>
<StackPanel Orientation="Vertical">
<TextBox x:Name="txtSearch" TextChanged="txtSearch_TextChanged"/>
<TextBlock x:Name="txtSummary" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Bottom" FontSize="8"></TextBlock>
<ListBox ItemsSource="{Binding Source={StaticResource cvs}}" DisplayMemberPath="First"/>
</StackPanel>
</Window>
这是我的代码隐藏(请不要介意这个代码隐藏,在实际应用程序中,我在这个场景中使用了最好的 MVVM)。
public partial class ListBoxFilterUsingCollectionViewSource : Window
{
private string _text="";
private readonly CollectionViewSource _viewSource;
public ListBoxFilterUsingCollectionViewSource()
{
InitializeComponent();
_viewSource = this.FindResource("cvs") as CollectionViewSource;
}
private void CollectionViewSource_Filter(object sender, FilterEventArgs e)
{
var character = e.Item as Character;
e.Accepted = character != null && character.First.ToLower().Contains(_text.ToLower());
}
private void txtSearch_TextChanged(object sender, TextChangedEventArgs e)
{
_text = txtSearch.Text;
_viewSource.View.Refresh();
SetSummary();
}
private void SetSummary()
{
var initialCount = 10; //HELP????
var filteredCount = 10; //HELP????
txtSummary.Text = String.Format("{0} of {1}", filteredCount, initialCount);
}
}
问题: 我在编写“SetSummary”方法时需要帮助,其中我可以从 CollectionViewSource 对象中获取“initialCount”和“filteredCount”。
感谢您的关注。