Filtering collections from XAML using CollectionViewSource

by Nico 12. April 2012 17:18

I find that I often run into the need of separating a collection of items into several collections just so I can bind them to multiple listboxes, for example a list of sessions spanning several tracks and each track is shown in his own listbox in a pivotitem. To get this done you can start by adding multiple collections to your viewmodel and divide the items there. However this makes your viewmodel very big in a very short time. A better way to do this is using CollectionViewSource items in XAML. Let me show you how.

First thing I did was building a demo class existing out of a title and a description, these two properties will be shown in the listbox later on. A third property is the one we’ll use to filter the data, here’s the completed class.

public class DemoClass
{
    public string Title { get; set; }
    public string Description { get; set; }
    public Pivot PivotToAppearIn { get; set; }
}

Nothing special here. Notice the Pivot instance, this is just an Enum that will be the way to filter later on.

public enum Pivot
{
    First,
    Second,
    All
}

For the demo’s purpose I’ll be creating a bunch of dummy data in the viewmodel. The project template I’ve used here is the default pivot app template in the Windows Phone 7.1.1 SDK. It comes with a bunch of dummy data, I’ve used the same data but put them in instances of the DemoClass. Those instances are put inside an ObservableCollection.

This is the viewmodel

public class MainViewModel : INotifyPropertyChanged
{
    public const string ItemsPropertyName = "Items";
    private ObservableCollection<DemoClass> items;
    public ObservableCollection<DemoClass> Items
    {
        get
        {
            return items;
        }

        set
        {
            if (items == value)
            {
                return;
            }

            items = value;
            NotifyPropertyChanged(ItemsPropertyName);
        }
    }

    public MainViewModel()
    {
        this.Items = new ObservableCollection<DemoClass>();
        LoadData();
    }

    public void LoadData()
    {
        Items.Add(new DemoClass 
        { 
            Title = "runtime one", 
            Description = "Maecenas praesent accumsan bibendum", 
            PivotToAppearIn = Pivot.First 
        });
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(String propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (null != handler)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

So we’ve got our basic bindable property here and a method that loads in the dummy data. In the demo project there’s obviously more then one item in the collection, there’s about 16 to be precise.

In the design I didn’t change a lot from the default template. I’ve just copied the ItemTemplate from the listbox to the pageresources so that it can be reused in the second listbox.

This is the template.

<phone:PhoneApplicationPage.Resources>
    <!-- template for the listboxes -->
    <DataTemplate x:Name="ListBoxTemplate">
            <StackPanel Margin="0,0,0,17" Width="432" Height="78">
                <TextBlock Text="{Binding Title}" TextWrapping="Wrap" 
                           Style="{StaticResource PhoneTextExtraLargeStyle}"/>
                <TextBlock Text="{Binding Description}" TextWrapping="Wrap" 
                           Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
            </StackPanel>
        </DataTemplate>
</phone:PhoneApplicationPage.Resources>

All right now that the preparations are set, time to get into the filtering. First step is to add a CollectionViewSource for each listbox. These are set on the same place as I’ve put the listbox ItemTemplate, in the pageresources. For this demo I need two CollectionViewSources.

<CollectionViewSource x:Name="FirstPivot" Filter="FirstPivot_Filter" Source="{Binding Items}" />
<CollectionViewSource x:Name="SecondPivot" Filter="SecondPivot_Filter" Source="{Binding Items}" />

So what’s all this? x:Name is like in any other XAML object, it’s just the name that can be used to reference the object. The source is the ObservableCollection that was created in the viewmodel. And last but definitely not least is the Filter event. This event will fire for every item in the collection that is bound to the Source property.

Now for the event handler, I’ll just post the event handler FirstPivot_Filter here because they are basically the same.

private void FirstPivot_Filter(object sender, System.Windows.Data.FilterEventArgs e)
{
    e.Accepted = (e.Item as DemoClass).PivotToAppearIn == Model.Pivot.First || 
        (e.Item as DemoClass).PivotToAppearIn == Model.Pivot.All;
}

FilterEventArgs has two properties, Accepted is a boolean that when true shows the item in the listbox that is bound to the CollectionViewSource. Item is the current item in the collection. Remember that this event is triggered for each item in the collection. So what we do here is casting the Item property to an instance of DemoClass then check if the PivotToAppearIn property, that was an instance of the enum, is either First or All.

Now that we have the CollectionViewSources and the event handlers in place it’s time to bind the ViewSource to the listbox.

<controls:PivotItem Header="first">
    <ListBox x:Name="FirstListBox" Margin="0,0,-12,0" 
             ItemsSource="{Binding Source={StaticResource FirstPivot}}"
             ItemTemplate="{StaticResource ListBoxTemplate}" />
</controls:PivotItem>

The bindingsource of ItemsSource is bound to the CollectionViewSource that filters for this listbox. And that’s it!

 

In this article I’ve shown how you can filter a collection using a CollectionViewSource in XAML. This is an easy and fast way to visually filter data while keeping a clean ViewModel.

Download the Demo project here.

Tags:

.Net | Binding | MVVM Light | Windows 8 | XAML | WP7 | WP8 | Silverlight | Metro | Devices

Not another rant on Windows 8

by Nico 14. March 2012 21:58

So Windows 8 consumer preview is available for a couple of weeks now and I see a lot of different reactions. Most negative reactions I’m seeing is about the Metro UI. I don’t understand why people don’t like it, personally I love the Metro UI and here’s why.

First of all, stop begging Microsoft to bring back the old Start menu. This is called innovation people, if Microsoft never changed the UI of Windows we would all still be working on this:

So nothing wrong with some good innovation. Yes I know that change can be scary, but just really how different is Windows 8 from Windows 7? When you take a closer look at it Windows 8 takes features from Windows 7 that have proven their worth and improves on them.

Don’t believe me? Let’s take the Start menu for example. The Windows 7 start menu has this really great feature that is the search box. Hit the Windows key on the keyboard, type the name or part of the name of the application you want to open and Windows performs a real-time search with the results being displayed inside of the start menu.

You can do the same in Windows 8, when on the Metro UI just start typing and Windows starts the same real-time search with the results being displayed in the Metro UI. So more space for the results and you can even specify where you want to search, on your pc, in your mails, on the web, etc. all from the same feature that we’ve come to know and love in Windows 7.

The Start menu in Windows 7 has a great way of showing your most used applications so you can easily access them. The Start screen in Windows 8 lets you organise and order every application in the way you prefer and makes you feel most comfortable. Another good concept made great.


The Windows 7 Start menu has some links to administrative tools like the Control Panel, Devices and Printers, Computer, … stuff that is only used by those who know what they’re for, so it’s mostly wasted space. In Windows 8 all these options and a lot more are hidden behind a right-click context menu, something the power users will definitly find and won’t bug the “normal” users.

  VS 

Next on the list of big improvements is the “All Programs” option in the Windows 7 Start menu, this just lists all folders inside of the Program Files and Program Files (x86) directories, it should be called “All Directories” instead of All Programs. Also due to the rather small nature of the Start menu only about 20 items can be seen without scrolling and they are really tiny. In Windows 8 I can place up to 60 items on one screen without scrolling, even when I divide them all into groups I get way more apps in my Start screen and it’s the shortcuts to the app themselves, not their installation folder.

VS

Enough about the Start menu and the Start screen. Let’s take a look at Windows explorer. The explorer in Windows 7 had some nice shortcuts depending on where you are. For example when you open “Computer” you get this:

Really cool way to get to System Properties, Control Panel, map a network drive, etc. Now in Windows 8 they’ve implemented the Ribbon like it exists in Office 2007 and 2010. However since some people out there don’t like the Ribbon for some obscure reason it starts collapsed.

After a click on the small white arrow in the upper right corner it turns into this:

Same options but more visually. The fact that they are bigger and have an icon makes them more accessible.

Now let’s take a look at some features that are new to Windows 8. For example, when you right click on the metro UI there’s an option to show all apps. On this overview when you click the zoom button in the bottom right corner you can select a letter or a group to quickly jump the applist to your selection.

Another new feature is the charms bar. This appears when you place the mouse cursor in the upper right corner of the screen, or on a touchscreen you can draw the bar in from the right. This bar contains a Start button that will take you to the Start screen. It has a Search button which does the obvious. The devices button shows all plugged in devices like printers, scanners, secondary monitors, etc. The Settings button shows options like volume, wireless networks, etc. Most of these are also available on the Desktop, just like on Windows 7.

The most impressive feature however is the Share button. The function of this button differs depending on what you’re doing. Let’s say for example that you’re reading a cool article on your favorite blog. Click the Share button and you can immediately share the article with some friends using the Mail application

At the moment this Share option only works on Metro apps, developers can build in the Share possibilities themselves.

Another feature of the Start screen that is completely new is the Store. Windows now has an online store where you can download apps. These apps are called Metro application and can only run in full screen or snapped next to another app. When you download an app from the store you can rest assure that the app is thoroughly tested on performance and capabilities. No viruses, spyware or other scary stuff in those apps, only clean good running apps.

A side note on Metro apps: a bunch of them has a so called App bar, just right-click in the app to bring it up. Since those applications run in full screen there is no close button. The apps can be closed by pressing Alt-F4 or by dragging the app from the top of the screen (where the titlebar would be in a normal app) to the bottom of the screen.

Now pay attention class, the next part could be important. The Metro applications can be closed if you want to but why would you? Windows 8 Metro apps work a lot like iOS and WP7 apps. When you press the Windows button on your keyboard you go back to the Start screen and the application itself stays in memory in a so called Tombstoned state. This means that it utilizes a bit of memory to keep alive but uses no CPU. If Windows notices that it doesn’t have enough free memory it will start closing the oldest tombstoned apps. I’ve told you that all Metro apps are tested by Microsoft, this includes a memory test that makes sure that an app doesn’t utilize more memory then is allowed. So please consider using the tombstoned state, Metro is designed this way and stop ranting that Metro apps can’t be closed because they can but they shouldn’t.

With that I would like to conclude this post. I hope I’ve shown you that Windows 8 is really worth looking into and that it’s a huge step forward. Microsoft is going for unity among platforms, the so called 3-screen strategy where phone, pc and television (Xbox360) all work in the same way. If you ask me why I like Windows 8 so much the answer would be because it changes everything and nothing at the same time. Everyone can keep working like they always have but the changes they’ve made are all made to make everyone more productive. And it works.

My final message: Stop saying that Windows 8 sucks. Install it on a VHD, second partition or second hard drive and use it for at least 2 weeks for all your daily work. That is the ONLY way to get a decent view on how it works. And please, do not install it in a virtual machine, make 2 clicks and rant on every forum you can find about how you don’t want the Metro UI.

Tags:

Windows 8 | Devices | Metro

Windows 8–the road so far

by Nico 10. February 2012 15:57

So it’s official, the Windows 8 beta, nicknamed Consumer Preview, will hit the worldwide web on February 29th. Time to list what we know so far.

For consumers:

  • the classic start menu has been replaced by a Metro interface, still unsure if there will be an option to bring back the classic menu
  • the windows desktop has now been extracted from the kernel and is just an app
  • Windows 8 utilizes much less resources then Windows 7, allowing it to run smoothly on weaker hardware
  • boot time is impressive, it takes mere seconds to launch. The cause is the fact that Windows 8 doesn’t shutdown completely, it’s kernel goes into hibernation. When you do a hard reset of the device you’ll notice that booting takes more time but it’s still noticeably faster than Win 7
  • Windows 8 will have two types of applications, the classic ones like we know them on Win 7 and Metro style applications. These Metro apps run completely full screen, no chrome like titlebars or borders
  • Metro apps run either full screen or snapped, running side by side with another app (even desktop apps)
  • Windows 8 comes with it’s very own Marketplace. Here you can download all kinds of Metro style applications
  • the ribbon that has been in Office since version 2007 now makes it’s way into the Windows explorer but it will be collapsed by default
  • Pinball and solitaire are installed games by default. Available in the store at launch will be:
    • Hydro Thunder
    • Toy Soldiers
    • Reckless Racing
    • Angry Birds
    • Ilomilo
    • Rocket Riot
    • Full House Poker
    • Tentacles
    • Crash Course
    • Ms Splosion Man
    • Wordament
  • Following apps will be included in the Consumer Preview
    • Camera
    • Messaging
    • Mail
    • Calendar
    • SkyDrive
    • People
    • Photos
    • Video
    • Music
  • Win 8 will be available on x86/x64 cpu’s and for the first time on ARM, mostly used in tablets
  • ARM versions of Windows will have both desktop and metro interface and comes with Office 15, a new Office version
  • Your profile (settings, wallpaper, …) will be synched to skydrive so that every time you buy a new Win 8 pc you don’t need to set everything manually
  • Refresh and Reset options, a refresh will keep all files and folders but will put Windows back in a fresh installed state, removing all installed applications and settings while a reset will do the same but also deletes all files and folders for all profiles
  • native USB 3.0 support
  • Windows 8 can mount and browse ISO and VHD files
  • UEFI Safe boot to prevent boot sector virusses
  • full backwards compatibility

For Developers:

  • anyone with XAML experience will be able to build Metro apps
  • Metro style takes a lot of the concepts of Windows Phone 7 and Silverlight
  • Instead of using the dreadful Win32 API developers can now use WinRT which provides a much cleaner way to interact with the OS
  • Metro apps are NOT .net code
  • .net 4.5 is included in Win 8
  • Metro apps in C#/VB/C++ + XAML or Javascript + HTML

 

Windows 8 will be pretty different compared to win 7. The developer preview has been out since September and I’ve been using it on a Iconia Tab W500 tablet since December. At the time I started using it I also had an iPad 2 but there’s just something special about a full blown OS on a tablet device, especially when running Win 8. I like the OS so far. The developer preview has lots of bugs, obviously, so I’m very curious about the performance and stability of the Consumer preview. Due to the stability problems I haven’t spend much time developing metro apps, this will change with the consumer preview. I’ll probably start by converting my WP7 apps to Win 8. More about that when I get to it.

Tags:

.Net | Windows programming | Windows 8 | Metro

About the author

Hi,

My name is Nico, I’m an MCP living in Belgium.
I’m currently employed as a .Net Software Developer at RealDolmen, one of Belgium’s leading IT single source providers.

I'm also founding member and board member of the Belgian Windows Phone User Group. If you're in Belgium feel free to drop by if we're doing an event. http://www.wiphug.be

This blog will be about Windows Phone 7, C#, XNA , WPF, Silverlight, and much more!

I hope to get feedback from my readers either through comments, mail (nico_vermeir@hotmail.com), twitter, facebook, …

 

Month List