This commit is contained in:
Beatriz Stollnitz 2019-08-05 18:06:10 -07:00
Родитель 470c6ddf61
Коммит 711e85bd25
16 изменённых файлов: 734 добавлений и 0 удалений

Просмотреть файл

@ -0,0 +1,9 @@
<Application x:Class="FilterSample.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="Window1.xaml"
>
<Application.Resources>
</Application.Resources>
</Application>

Просмотреть файл

@ -0,0 +1,17 @@
using System;
using System.Windows;
using System.Data;
using System.Xml;
using System.Configuration;
namespace FilterSample
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : System.Windows.Application
{
}
}

Просмотреть файл

@ -0,0 +1,89 @@
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{7C873700-77D9-47FB-B91B-4CCE71A98DCD}</ProjectGuid>
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<RootNamespace>FilterSample</RootNamespace>
<AssemblyName>FilterSample</AssemblyName>
<WarningLevel>4</WarningLevel>
<OutputType>winexe</OutputType>
<MinFrameworkVersionRequired>3.0</MinFrameworkVersionRequired>
<Install>true</Install>
<InstallFrom>Web</InstallFrom>
<UpdateEnabled>true</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>false</MapFileExtensions>
<ApplicationVersion>1.0.0.*</ApplicationVersion>
<IsWebBootstrapper>true</IsWebBootstrapper>
<BootstrapperEnabled>true</BootstrapperEnabled>
<PublishUrl>Publish\</PublishUrl>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>.\bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugSymbols>false</DebugSymbols>
<Optimize>true</Optimize>
<OutputPath>.\bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
<Reference Include="WindowsBase" />
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
<Reference Include="UIAutomationProvider" />
<Reference Include="UIAutomationTypes" />
<Reference Include="ReachFramework" />
<Reference Include="System.Printing" />
<Reference Include="System.ServiceModel" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.IdentityModel" />
</ItemGroup>
<ItemGroup>
<ApplicationDefinition Include="App.xaml" />
<Page Include="Window1.xaml" />
<Compile Include="App.xaml.cs">
<DependentUpon>App.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
<Compile Include="Window1.xaml.cs">
<DependentUpon>Window1.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
</Compile>
<AppDesigner Include="Properties\" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="$(MSBuildBinPath)\Microsoft.WinFX.targets" />
</Project>

Просмотреть файл

@ -0,0 +1,20 @@

Microsoft Visual Studio Solution File, Format Version 9.00
# Visual Studio 2005
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FilterSample", "FilterSample.csproj", "{7C873700-77D9-47FB-B91B-4CCE71A98DCD}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{7C873700-77D9-47FB-B91B-4CCE71A98DCD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7C873700-77D9-47FB-B91B-4CCE71A98DCD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7C873700-77D9-47FB-B91B-4CCE71A98DCD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7C873700-77D9-47FB-B91B-4CCE71A98DCD}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

Двоичные данные
28-FilterSample/FilterSample/FilterSample.suo Normal file

Двоичный файл не отображается.

Просмотреть файл

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace FilterSample
{
public class GreekGod
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private string description;
public string Description
{
get { return description; }
set { description = value; }
}
private string romanName;
public string RomanName
{
get { return romanName; }
set { romanName = value; }
}
public GreekGod(string name, string description, string romanName)
{
this.name = name;
this.description = description;
this.romanName = romanName;
}
}
}

Просмотреть файл

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Data;
using System.Collections.ObjectModel;
namespace FilterSample
{
public class GreekGods : ObservableCollection<GreekGod>
{
public GreekGods()
{
this.Add(new GreekGod("Aphrodite", "Goddess of love, beauty and fertility", "Venus"));
this.Add(new GreekGod("Apollo", "God of prophesy, music and healing", "Apollo"));
this.Add(new GreekGod("Ares", "God of war", "Mars"));
this.Add(new GreekGod("Artemis", "Virgin goddess of the hunt", "Diana"));
this.Add(new GreekGod("Athena", "Goddess of crafts and the domestic arts", "Athena"));
this.Add(new GreekGod("Demeter", "Goddess of agriculture", "Ceres"));
this.Add(new GreekGod("Dionysus", "God of wine", "Bacchus"));
this.Add(new GreekGod("Hephaestus", "God of fire and crafts", "Vulcan"));
this.Add(new GreekGod("Hera", "Goddess of marriage", "Juno"));
this.Add(new GreekGod("Hermes", "Messenger of the Gods", "Mercury"));
this.Add(new GreekGod("Poseidon", "God of the sea, earthquakes and horses", "Neptune"));
this.Add(new GreekGod("Zeus", "Supreme God of the Olympians", "Jupiter"));
}
}
}

Просмотреть файл

@ -0,0 +1,54 @@
#region Using directives
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Resources;
using System.Globalization;
using System.Windows;
using System.Runtime.InteropServices;
#endregion
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("FilterSample")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FilterSample")]
[assembly: AssemblyCopyright("Copyright @ 2006")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.*")]

Просмотреть файл

@ -0,0 +1,70 @@
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.42
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------
namespace FilterSample.Properties
{
using System;
using System.IO;
using System.Resources;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the Strongly Typed Resource Builder
// class via a tool like ResGen or Visual Studio.NET.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
class Resources
{
private static System.Resources.ResourceManager _resMgr;
private static System.Globalization.CultureInfo _resCulture;
/*FamANDAssem*/
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public static System.Resources.ResourceManager ResourceManager
{
get
{
if ((_resMgr == null))
{
System.Resources.ResourceManager temp = new System.Resources.ResourceManager("Resources", typeof(Resources).Assembly);
_resMgr = temp;
}
return _resMgr;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public static System.Globalization.CultureInfo Culture
{
get
{
return _resCulture;
}
set
{
_resCulture = value;
}
}
}
}

Просмотреть файл

@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

Просмотреть файл

@ -0,0 +1,42 @@
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.42
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------
namespace FilterSample.Properties
{
public partial class Settings : System.Configuration.ApplicationSettingsBase
{
private static Settings m_Value;
private static object m_SyncObject = new object();
public static Settings Value
{
get
{
if ((Settings.m_Value == null))
{
System.Threading.Monitor.Enter(Settings.m_SyncObject);
if ((Settings.m_Value == null))
{
try
{
Settings.m_Value = new Settings();
}
finally
{
System.Threading.Monitor.Exit(Settings.m_SyncObject);
}
}
}
return Settings.m_Value;
}
}
}
}

Просмотреть файл

@ -0,0 +1,7 @@
<?xml version='1.0' encoding='iso-8859-1'?>
<SettingsFile xmlns="uri:settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>

Просмотреть файл

@ -0,0 +1,22 @@
<Window x:Class="FilterSample.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="FilterSample" Width="300" Height="380"
xmlns:local="clr-namespace:FilterSample"
>
<Window.Resources>
<local:GreekGods x:Key="src1"/>
<local:GreekHeroes x:Key="src2"/>
<CollectionViewSource Source="{StaticResource src2}" x:Key="cvs" Filter="FilterOutB"/>
</Window.Resources>
<Border Margin="30" BorderBrush="Blue" BorderThickness="2" Padding="10">
<StackPanel>
<Label>Items that start with "A" are filtered out:</Label>
<ListBox ItemsSource="{Binding Source={StaticResource src1}}" DisplayMemberPath="RomanName"/>
<Label>Items that start with "B" are filtered out:</Label>
<ListBox ItemsSource="{Binding Source={StaticResource cvs}}" DisplayMemberPath="HeroName"/>
</StackPanel>
</Border>
</Window>

Просмотреть файл

@ -0,0 +1,138 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.ComponentModel;
namespace FilterSample
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : System.Windows.Window
{
public Window1()
{
InitializeComponent();
object src1 = this.Resources["src1"];
ICollectionView collectionView = CollectionViewSource.GetDefaultView(src1);
collectionView.Filter = new Predicate<object>(FilterOutA);
}
public bool FilterOutA(object item)
{
GreekGod gg = item as GreekGod;
if ((gg == null) || gg.RomanName.StartsWith("A"))
{
return false;
}
else
{
return true;
}
}
private void FilterOutB(object sender, FilterEventArgs e)
{
GreekHero gh = e.Item as GreekHero;
if ((gh == null) || gh.HeroName.StartsWith("B"))
{
e.Accepted = false;
}
else
{
e.Accepted = true;
}
}
}
public class GreekGod
{
private string name;
public string Name
{
get { return name; }
}
private string description;
public string Description
{
get { return description; }
}
private string romanName;
public string RomanName
{
get { return romanName; }
}
public GreekGod(string name, string description, string romanName)
{
this.name = name;
this.description = description;
this.romanName = romanName;
}
}
public class GreekGods : ObservableCollection<GreekGod>
{
public GreekGods()
{
this.Add(new GreekGod("Aphrodite", "Goddess of love, beauty and fertility", "Venus"));
this.Add(new GreekGod("Apollo", "God of prophesy, music and healing", "Apollo"));
this.Add(new GreekGod("Ares", "God of war", "Mars"));
this.Add(new GreekGod("Artemis", "Virgin goddess of the hunt", "Diana"));
this.Add(new GreekGod("Athena", "Goddess of crafts and the domestic arts", "Athena"));
this.Add(new GreekGod("Demeter", "Goddess of agriculture", "Ceres"));
this.Add(new GreekGod("Dionysus", "God of wine", "Bacchus"));
this.Add(new GreekGod("Hephaestus", "God of fire and crafts", "Vulcan"));
this.Add(new GreekGod("Hera", "Goddess of marriage", "Juno"));
this.Add(new GreekGod("Hermes", "Messenger of the Gods", "Mercury"));
this.Add(new GreekGod("Poseidon", "God of the sea, earthquakes and horses", "Neptune"));
this.Add(new GreekGod("Zeus", "Supreme God of the Olympians", "Jupiter"));
}
}
public class GreekHero
{
private string heroName;
public string HeroName
{
get { return heroName; }
}
public GreekHero(string heroName)
{
this.heroName = heroName;
}
}
public class GreekHeroes : ObservableCollection<GreekHero>
{
public GreekHeroes()
{
this.Add(new GreekHero("Bellerophon"));
this.Add(new GreekHero("Hercules"));
this.Add(new GreekHero("Jason"));
this.Add(new GreekHero("Odysseus"));
this.Add(new GreekHero("Perseus"));
this.Add(new GreekHero("Theseus"));
}
}
}

Двоичные данные
28-FilterSample/Images/28FilterSample.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 12 KiB

82
28-FilterSample/README.md Normal file
Просмотреть файл

@ -0,0 +1,82 @@
# How to filter items from a collection
Today I will show you two ways of using the filter feature of data binding.
There are two ObservableCollections of items in this sample. The first one contains a list of GreekGods, and the ListBox that displays it shows their Roman names. The second one contains a list of GreekHeroes. I will use these two collections to show two different ways of filtering items.
I decided to filter out all items that start with "A" from the first collection. I started out by adding a new instance of the GreekGods collection to the resources and bound a ListBox's ItemsSource to that collection:
<Window.Resources>
<local:GreekGods x:Key="src1"/>
(...)
</Window.Resources>
<Label>Items that start with "A" are filtered out:</Label>
<ListBox ItemsSource="{Binding Source={StaticResource src1}}" DisplayMemberPath="RomanName"/>
In the constructor for the Window, I added code after initialization to get the default view for this collection. Remember that we never bind directly to the collection; there is always a view on top of that collection that we bind to. In this case I am not creating that view explicitly with the help of a CollectionViewSource, so a default view is created behind the scenes. I can get to that default view by using the GetDefaultView static method of CollectionViewSource:
public Window1()
{
InitializeComponent();
object src1 = this.Resources["src1"];
ICollectionView collectionView = CollectionViewSource.GetDefaultView(src1);
collectionView.Filter = new Predicate<object>(FilterOutA);
}
Once I have a handle to the view, I am able to set its Filter property to the Predicate&lt;object&gt; callback function below:
public bool FilterOutA(object item)
{
GreekGod gg = item as GreekGod;
if ((gg == null) || gg.RomanName.StartsWith("A"))
{
return false;
}
else
{
return true;
}
}
This method is called once for each item. If the item is a GreekGod whose Roman name begins with "A", it will return false, and that item will be filtered out. Otherwise, it will return true and the item will be displayed.
Similarly, I decided to filter out all items that start with B from the second collection. However, this time I am using CollectionViewSource explicitly. I set the Source property of the CollectionViewSource to the collection and bind the ListBox's ItemsSource to the CollectionViewSource:
<Window.Resources>
(...)
<local:GreekHeroes x:Key="src2"/>
<CollectionViewSource Source="{StaticResource src2}" x:Key="cvs" Filter="FilterOutB"/>
</Window.Resources>
<Label>Items that start with "B" are filtered out:</Label>
<ListBox ItemsSource="{Binding Source={StaticResource cvs}}" DisplayMemberPath="HeroName"/>
We came up with the CollectionViewSource class to serve two purposes: 1) To allow us to do view related operations in XAML, such as grouping, sorting, filtering or creating a custom view of a certain type and 2) To serve as a container for all the view methods, such as GetDefaultView or IsDefaultView. Before we came up with this class these methods were in the Binding class, which cluttered it with unrelated methods and made it hard for users to find them.
I've been asked several times about the difference between CollectionView and CollectionViewSource. The difference is simple: CollectionViewSource is not a view, but a class that contains handles to the source and the corresponding view and is used for the purposes I described above. CollectionView is an actual view on top of a collection, which contains information about the current item, filtering, sorting and grouping.
Unfortunately you still need code to specify which items are filtered in or out:
private void FilterOutB(object sender, FilterEventArgs e)
{
GreekHero gh = e.Item as GreekHero;
if ((gh == null) || gh.HeroName.StartsWith("B"))
{
e.Accepted = false;
}
else
{
e.Accepted = true;
}
}
Note that the Filter property in CollectionViewSource is not a delegate like the one in CollectionView, but an event handler. We made this decision so that you could specify the name of the filter method in XAML. At this point, there is no support to add the name of the callback method of a delegate in XAML, but this support exists for events. We realize that the two ways of filtering are a little inconsistent, but this design brings us closer to our goal of allowing the user to do as much as possible in XAML with CollectionViewSource.
The filter event handler has a FilterEventArgs argument, which has two interesting properties: the Item property that provides the item on which we need to make the filter decision, and the Accepted property where we set the result of that decision. If we set Accepted to false, the item will be filtered out, and if we set it to true, the item will be displayed.
Here is a screenshot of the completed sample:
![](Images/28FilterSample.png)