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

Make your WP7.5 app run on low-end devices

by Nico 28. February 2012 20:54

On MWC the first Windows Phone Tango devices were announced. The Nokia Lumia 610 and the ZTE Orbit are low-end devices running on only 256MB of RAM. This is made possible thanks to a new, lower end version of the Windows Phone platform. Developers need to make their applications available for either low-end or high-end devices or both. This is determined by the memory usage of the application and if it’s set in the manifest file. Since the new devices only have 256MB of ram your application can use a maximum of 90MB according to the developer guidelines. The memory consumption of your application can be tested with the marketplace test kit by right clicking on your WP7.5 project in Visual Studio 2010.

The refresh of the WP7.1 SDK includes a second emulator running on the low end version of Windows Phone. With this developers can now test if their applications will keep running on the cheaper devices. If not, the user will get an error when trying to install your application stating that it won’t run on their low-end device. Users with a mid –or high-end device can keep using your app without any problems.

This is in fact the same emulator but running on a different image. After installing the update you won’t be able to launch the emulator from the Windows start menu anymore, to fix this add either –256 or –512 to the shortcut depending on what image you want to load in the emulator.

With that, let’s dive into some code and figure out what we can do on the low-end device.

I’ve created a demo project that on launch checks for the available amount of memory using a Device Extended Property from the new SDK called ApplicationWorkingSetLimit. I’ve poured this into a method that sets a private boolean to true if it’s a low-end device

Code Snippet
  1. private void CheckWP7Version()
  2. {
  3.     //check if the device is low-end
  4.     long result = (long) DeviceExtendedProperties.GetValue("ApplicationWorkingSetLimit");
  5.  
  6.     if (result < 94371840)
  7.     {
  8.         isLowEndDevice = true;
  9.     }
  10.     else
  11.     {
  12.         isLowEndDevice = false;
  13.     }
  14. }

Note that the ApplicationWorkingSetLimit is a hardcoded string, so be very careful of typos. The 94371840 is the maximum amount of bytes my application can use on a low-end device.

Another limitation of Windows Phone Tango is that it currently does not support background agents and that includes both periodic tasks as well as resource intensive tasks. When you try to add a background agent on a low-end device you get this:

That’s not a very clear error message is it? The inner exception doesn’t tell us much more. This will probably change once the new SDK is completely finished. So when you’re using background tasks in your application, please update your app with checks of the version. Don’t submit the update to the marketplace just yet because the current CTP version of the SDK doesn’t have a go-live license so it won’t pass marketplace certification.

My example is an app that will set a random count to the application’s tile if it’s pinned to the start screen. In debug mode it will do this every 30 seconds. When you install it on the 256MB version of the emulator it won’t be able to register the agent, in fact it won’t even try because I have a build-in check for low memory devices.

In my example I’ve used a boolean to store whether or not the device has low memory. This works because my app only has one page. In a real life application it would be better to store this into the IsolatedStorageSettings using this code.

Code Snippet
  1. private void CheckWP7Version()
  2. {
  3.     bool isLowEndDevice;
  4.  
  5.     //check if the device is low-end
  6.     long result = (long)DeviceExtendedProperties.GetValue("ApplicationWorkingSetLimit");
  7.  
  8.     if (result < 94371840)
  9.     {
  10.         isLowEndDevice = true;
  11.     }
  12.     else
  13.     {
  14.         isLowEndDevice = false;
  15.     }
  16.  
  17.     if (IsolatedStorageSettings.ApplicationSettings.Contains("IsLowEndDevice"))
  18.     {
  19.         IsolatedStorageSettings.ApplicationSettings["IsLowEndDevice"] = isLowEndDevice;
  20.     }
  21.     else
  22.     {
  23.         IsolatedStorageSettings.ApplicationSettings.Add("IsLowEndDevice", isLowEndDevice);
  24.     }
  25.  
  26. }

And load the value anywhere in your application again like this

Code Snippet
  1. var isLowEndDevice = IsolatedStorageSettings.ApplicationSettings["IsLowEndDevice"];

If for some reason your application can’t run on low-end devices you can block those devices from downloading it. To do this you need to add some lines to the application’s manifest file, right below the capabilities.

Code Snippet
  1. <Requirements>
  2.   <Requirement Name="ID_REQ_MEMORY_90" />
  3. </Requirements>

With this in place the low-end devices will get a message stating that their device is not suited to run your application.

I hope I gave you a good overview about what to expect with the new low-end devices and that you can adjust your applications to support these devices. Don’t be too worried about the memory limitations on the new devices, Microsoft scanned all available applications and found only 5 that utilise too much memory, they’ve contacted the developers and are working together with them to overcome these problems.

The solution of my example can be found here(SkyDrive link).

Tags:

XAML | WP7 | Metro | Devices | .Net

BlockAddiction V2.0 online now

by Nico 23. February 2012 07:47

Version 2.0 of BlockAddiction has passed marketplace certification and is available for download now. The biggest change is the all new Time Attack mode where you have to survive for 60 seconds and score as high as possible. Game Over means no score.

BlockAddiction has reached well over 400 downloads and is available on Windows Phone marketplace (Link).

I was thinking about an About page and advertising but I figured ads could ruin the experience and I completely forgot about the About page. Glimlach I might add it in the future but for now my focus shifted to some other projects.

If you’ve got ideas, bug reports or some other feedback, leave a comment, contact me via Twitter or send me a mail!

Tags:

XNA | WP7 | .Net | Devices

Windows Phone 8, first official details!

by Nico 2. February 2012 22:18

A video of Joe Belfiore detailing Windows Phone 8, codename “Apollo”, to Nokia has been leaked. The video has a bunch of rumors that are confirmed and some new features that will find their way into Microsoft’s next mobile OS.

The new features are:

  • Data Smart: your phone being smart about what network to use, this includes support for carrier wireless networks.
  • App-to-App communication. WP apps are sandboxed, in WP8 apps will be able to communicate with each other on a lower level then deeplinking by utilizing some sort of contracts.
  • Internet Explorer 10 Mobile. next gen mobile browser, based on the IE10 desktop kernel
  • Shared components with Windows 8. The kernel, multi-core processor support, sensor fusion, security model, network, and video and graphics technologies are all coming from Windows 8.
  • Companion experiences with Windows 8. the xbox companion app will be integrated into the system. Skydrive will have a deeper integration. All this will give the possibility to share content across phone, pc, console, … Also Zune will make place for some sort of new ActiveSync client, ow yeah! As much as I like Zune, activesync is just better.
  • Skype app. Still a separate but better app and not integrated into OS.
  • NFC and Wallet. Google wallet but coming from Microsoft, so obviously the same but better Glimlach Up to the carriers if they’ll support it. It will work both from build-in NFC chips or by special sim cards that have an on-board NFC chip
  • Local Scout. Now with personal recommendations and support for carrier hotspots.
  • Camera improvements. more powerful experience and some sort of “lens” app, we’ll have to wait and see what this means.
  • Business features. WP8 is targeting the  business again with features such as complete bitlocker encryption, secure boot check, system center integration, Exchange activesync policies and inventory possibilities. And, and this one’s kinda big, private appstores for businesses! That’s right, your in-house, employee only apps can be hosted on a private store.
  • For Developers: the CE kernel is boosted out in favor of the Windows 8 kernel, WP7 apps will be fully backwards compatible. With the new kernel comes support for native code, C++ developers rejoice! This makes porting ios and android apps easier and will make certain very popular apps finally come to our beloved platform.
  • Hardware: 4 resolutions, swappable SD card support, multicore CPU, NFC.

In my opinion, if Microsoft can deliver these features WP8 will be HUGE! This makes the Windows Phone platform on par with the competition and on some levels it exceeds them. Big kudos to Microsoft for making this happen in about 2 years, both Apple and Google have spent over 5 years to get to these kinds of functionality. Only two things remain in the dark, will our current devices get an upgrade? And will they pull this off? WP8 is rumored to roll out in the 4th quarter of 2012.

And remember Joe Belfiore, nothing remains hidden on the internet.

Tags:

WP7 | WP8 | Devices

Techdays Belgium 2012

by Nico 2. February 2012 08:27

So Techdays is right around the corner and I’ll be attending for the third time.I’ll be attending all kinds of sessions going from Windows 8 development to the complete deep dive track on web to my favorite subject, Windows Phone 7 development. I’m also excited about the Scott “The Gu” Guthrie doing the opening keynote and doing a session the second day. Also presenting this year is Laurent Bugnion, the father of the awesome MVVM Light framework.

Here’s the list of sessions I’ll be attending, this list is subject to change depending on if I change my mind the last minute, as I’m known to do sometimes Glimlach.

Tuesday February 14th

  • Opening keynote with Scott Guthrie
  • Welcome to the Metro Application Platform
  • Windows Phone Fast App Switching, Tombstoning and Multitasking
  • The Future of C# and Visual Basic
  • Devices + Cloud: Using Azure on iOS, Android, Windows Phone, …

Wednesday February 15th

  • ScottGu unplugged
  • Take a ride on the Metro
  • The zen of async: Best practices for best performance
  • MVVM Applied: From Silverlight to Windows Phone to Windows 8
  • MVVM & WCF RIA Services: an architectural story
  • Building a data intensive application

Thursday February 16th

This is a deep dive day, I’ll be following the web track that focuses on what’s new in ASP.net 4.5 and Visual Studio 11

 

Tags:

.Net | Presenting | WP7 | Windows programming | XAML | XNA | Web development | MVVM Light | Devices

Overview of WP7 devices

by Nico 25. January 2012 11:01

I’ve created an overview of all currently known Windows Phone devices. I’ll try to keep this as up-to-date as possible but don’t shoot me if it takes some time to add new devices to the list Glimlach.

Every device is linked to a site with all specifications. You can find the page by clicking the link on the right or by clicking here.

For those that are too lazy to check the page, I’ll paste the list here:

Name Release Date CPU speed Memory Display Notes
Acer Allegro November 2011 1 GHz 8GB 3.6" LCD No flash
Dell Venue Pro November 2010 1 GHz 8GB/16GB 4.1" AMOLED Portrait keyboard
Fujitsu Toshiba IS12T September 2011 1 GHz 32GB 3.7" LCD 13.2MP camera and waterproof
HTC Pro 7 January 2011 1 GHz 8GB/16GB 3.6" LCD  
HTC Surround November 2010 1 GHz 16GB 3.8" LCD slide out speaker
HTC Trophy October 2010 1 GHz 8GB/16GB 3.8" SLCD  
HTC Mozart October 2010 1 GHz 8GB/16GB 3.7" SLCD Xenon flash
HTC HD7 October 2010 1 GHz 8GB/16GB 4.3" SLCD  
HTC Titan October 2011 1.5GHz 16GB 4.7" SLCD  
HTC Titan II March 2012 1.5GHz 16GB 4.7" SLCD 16MP camera, 4G LTE
HTC Radar October 2011 1 GHz 8GB 3.8" SLCD  
LG Optimus 7 October 2010 1 GHz 16GB 3.8" LCD DLNA support
LG Quantum October 2010 1 GHz 16GB 3.5" LCD  
Nokia Lumia 710 November 2011 1.4 GHz 8GB 3.7" LCD  
Nokia Lumia 800 November 2011 1.4 GHz 16GB 3.7" ClearBlack AMOLED N9 design
Nokia Lumia 900 March 2012 1.4 GHz 16GB 4.3" ClearBlack AMOLED 4G LTE
Samsung Focus November 2010 1 GHz 8GB 4" Super AMOLED microSD support
Samsung Focus S November 2011 1.4 GHz 16GB 4.3" Super AMOLED  
Samsung Omnia 7 October 2010 1 GHz 8GB/16GB 4" Super AMOLED  
Samsung Omnia W November 2011 1.4 GHz 8GB 3.7" Super AMOLED  
ZTE Tania December 2011 1 GHz 4GB 4.3" LCD  

Tags:

Devices | WP7

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