Add Scrolling Event in a List – WP7

Many of you might have been in  a situation when you desperately wanted to know if a scroll bar is scrolling or not.

Currently there is no direct provision to attain this in WP7. I’ll walk through the code which will help you to identify if a list is scrolling or not. Later at the end there ia a full working sample attached.

My sample is straight forward. I’ll be changing the page title to “Scrolling” when we scroll the list and “NotScrolling” while it is stationary.

We have a list called theList.

1. Now attach a Loaded event to the page constructor:

public MainPage()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainPage_Loaded);
theList.ItemsSource = GetListData(60);
}

2. Define a variable to identify if ScrollEvent has been hooked already:

bool alreadyHookedScrollEvents = false;

3. Define MainPage_Loaded handler. All major work will be done here:

void MainPage_Loaded(object sender, RoutedEventArgs e)
{
if (alreadyHookedScrollEvents)
return;

alreadyHookedScrollEvents = true;

//This is the key player which holds the magic for this trick
//This ScrollViewer is the first templated child of your List
ScrollViewer viewer = FindSimpleVisualChild<ScrollViewer>(theList);

if (viewer != null)
{
// Visual States are always on the first child of the control template
FrameworkElement element = VisualTreeHelper.GetChild(viewer, 0) as FrameworkElement;
if (element != null)
{
VisualStateGroup group = FindVisualState(element, "ScrollStates");
if (group != null)
{
group.CurrentStateChanging += group_CurrentStateChanging;
}
}
}
}

4. Use this helper function to identify the first visual child (ScrollViewer):

T FindSimpleVisualChild<T>(DependencyObject element) where T : class
{
while (element != null)
{
if (element is T)
return element as T;
element = VisualTreeHelper.GetChild(element, 0);
}
return null;
}

5. Actual even handler which identify a changed state for scrollviewer:

void group_CurrentStateChanging(object sender, VisualStateChangedEventArgs e)
{
//for demonstration change page's title
PageTitle.Text = e.NewState.Name;
}

6. Helper function to filter out the required VisualState:

VisualStateGroup FindVisualState(FrameworkElement element, string name)
{
if (element == null)
return null;

IList<VisualStateGroup> groups = (IList<VisualStateGroup>)VisualStateManager.GetVisualStateGroups(element);
foreach (VisualStateGroup group in groups)
if (group.Name == name)
return group;

return null;
}

     
7. Another helper function to fill the data in list to demonstrate implementation:

ObservableCollection<int> GetListData(int count)
{
sourceList = new ObservableCollection<int>();
for (int i = 1; i <= count; i++)
{
sourceList.Add(i);
}
return sourceList;
}

     
Source Code

[Windows Phone 7.5] Dale calidad a tus aplicaciones con Expression Blend (I)

Hola a todos! Hoy vamos a conocer un poco mejor a un gran desconocido del desarrollo en Windows Phone 7.5: Expression Blend. No es necesario ser un experto diseñador para, usando Expression Blend, dar a nuestras aplicaciones un toque de calidad extra, una apariencia única y mejorar globalmente el acabado de nuestro producto. Una de las grandes ventajas de Expression Blend es que es capaz de trabajar con el mismo proyecto que usamos en Visual Studio, por lo que podremos crear nuestro…(read more)

Microsoft + Nokia Babies: Hate at a Distance, Love Up Close

original source: http://www.pop.com.br/

Apologies to QML fans but I’m going to to extend the interruption of that series by at least one more article.  Blame a cynical friend’s recent conversion to the Dark Side of mobile Microsoft 

As regular readers know I’ve been a dual Microsoft/Linux power user for many years.  While some friends see that as a bad case of cognitive dissonance, I prefer to call it technical agnosticism.  I was never interested though to include Windows Mobile in that scope, mainly due to an observance that it was just Windows scaled (badly) down to a handheld device rather than something specifically designed for the form factor.

Microsoft finally realized that, bit the bullet, and created Windows Phone from scratch.  But the product still carried Windows branding baggage and has been panned by some mobilists and tech pundits– many of whom did so with ten-foot virtual poles.

This has been especially true of Nokia fans (self included), particularly those who saw great things in the Linux-based operating systems Maemo and then MeeGo and had high hopes for the sexy N9.  Nokia’s CEO had brought about the Elopocalypse in accepting Steve Ballmer’s engagement offer, and no one from the Linux side of the family wanted to be part of the post-wedding reception.  Some later snickered at the Spanish meaning for “Lumia” (as tempting as it is to riff on that further, I’ll demur).

So far the MicroNokia nuptials have resulted in two acknowledged offspring: the fraternal Nokia Lumia twins, 710 and 800.  There’s nothing apparently spectacular about the 710, hardware- or appearance-wise.  Its low price is the most attractive feature.  As for the 800, photos don’t quite do it justice.  You have to use this device to realize its true beauty.

The same can be said for Microsoft’s Windows Phone 7 OS.  Yes, videos seem compelling, but jaded smartphone users aren’t easily impressed by moving pictures.  Experience it first-hand, however, and the skepticism melts.  I admit to encountering that at Nokia World when I first got to play with the Lumias.

This sort of mindset conversion is never more dramatic than when a diehard open source devotee is swayed.  Such was the case when my aforementioned friend Johan Paul surprisingly tweeted the following:

I’m highly interested in what he’ll have to say further, the more he uses his Lumia 800.

Now, I can’t quite profess unconditional love for these babies.  Some of the beauty is only skin-deep and there are genetic defects only a mother could overlook.  My personal OS peeves are no tethering, no Bluetooth file transfers and no USB mass storage mode.  HUGE step backwards in my opinion and a MUST fix.  As for the Lumia 800, lack of TV output combined with omission of a front-facing camera have my teeth gritted.  I also have to wonder why support for quickly-trending NFC was left out.

Beyond feature failures, Microsoft and Nokia face distinct but obviously related challenges here.  The former needs to get Windows Phone in general out of the market share basement.  The latter needs to re-establish their specific phones as must-have products.  I have yet to see a clear signal on how evangelical overlap is going to be handled by the two, particularly where software development is concerned.  I also still wonder if the marriage between them will ultimately put off other WP participants (not that I actually care).

Nevertheless, if outreach efforts can get examples into the hands of prospective buyers everywhere, even doubtful ones like my friend Johan, Microsoft and Nokia do indeed have a potentially winning combo.  The 25,000 device-seeding effort won’t hurt!  In addition to my QML explorations, I plan to develop for Windows Phone and can’t wait to start showing off my own Lumia 800.

I just need to get that pretty baby in my hands…

Filed under: Into Outreach, Inviting Change, Mentioning Maemo, Mentioning MeeGo, The Write Stuff, Views and Reviews Tagged: forumnokia, Johan Paul, LinkedIn, Lumia, Maemo, MeeGo, Microsoft, Nokia, Windows Phone

Improved support for non-English languages

While English is the native language of this wiki, we encourage developers to form communities around their own languages and to translate content to help those developers who aren’t so proficient with English.

We’ve recently been working to improve the support for non-English languages on the wiki. This month we’ve fixed printing of non-English characters in PDF – so now if you select "Download as PDF" in the wiki sidebar the resulting PDF will correctly display all charactes. Check it out for this Chinese topic: 使Windows Phone应用程序根据主题改变配色方案 - of course it works for Russian, Portuguese and Japanese too!

In addition, in my last post I highlighted that you can now add a link to translations of a topic and these will be displayed in the sidebar.

Using a script I’ve now added these translation links for most translations in Portuguese, Russian and Japanese. This makes it easy to see what has been translated, to find translations, and to jump to the original article to see if it has changed since translation. I’m still working on adding the links for Chinese topics – there are a lot of them, and in many cases there was no way to automatically "guess" what the original topic was using a script.

If you’re interested in translating articles or want to discuss further, add a response!

[Windows Phone 7.5] Personalizando la System Tray.

En Windows Phone 7.0 la system tray solo nos permitía especificar su visibilidad, esto es, si queríamos mostrar o no las indicaciones de batería, hora, cobertura, etc… personalmente siempre me ha gustado la opción de poder ver esta información, sobretodo si voy a estar mucho tiempo usando una aplicación. El mayor problema aparecía en el hecho de que el background / foreground era el dictado por el sistema y no existía forma de personalizarlo…(read more)

More Post-MeeGo Musing: Community Echoes

Ever since Intel’s MeeGo-cedes-to-Tizen announcement, I’ve been in a slightly unfocused state.  It’s familiar territory– when Maemo was set aside by Nokia for MeeGo, there was the same quandary: what now?  Better yet, what next?

After a little over two years of scant free time, I’m finally working normal hours.  So that liberates me for more community engagement, aka the stuff I really love.  It also frees me up to think.  But looking back on the past 5 years of support for open source projects with great promise but ultimate abandonment, I’m left to wonder what to target. 

I asked that question out loud not long ago and concluded that adding Windows Phone to my repertoire makes sense.  I already have the skills and connections.  But so does including Qt, and so I’ve been plunging into QML recently as I await the delivery of a Nokia WP phone for development.  I find that, in both cases, developer/enthusiast communities for both platforms are small and quiet in my area.  So I feel obligated to help build them up as I did for Maemo and MeeGo.

That last thought just makes me nostalgic for a time when inspiring those communities could be as simple as posting “Just wait until you see what’s next!” on a discussion forum or IRC chat.  The passion of Maemo and MeeGo advocates was undeniable.  Even their complaints betrayed high interest; most people who don’t really care about a product or project won’t give you much feedback.  They just leave.

I notice that the original Maemo community refuses to “just leave”.  At the very least, we lament on twitter the lost chances to see each other in person once or twice a year.  We hit each other up with connection requests on social media channels, as a friend did to me this morning, inspiring this post.

I’ve realized most of my true friends are nowhere close to my neighborhood.  They’re in Moscow and Tampere and Mexico City and New Delhi and Vancouver and Berlin and Beijing.  Sadly, one I’ll not see again.

Some in my former circles will do more than cling to contact via virtual means.  Many are already in Qt and I hope to encourage more to try the waters.  A few will venture into Windows Phone, especially Nokia Developer Champions transitioning from Symbian.  Others have or will find homes in other related ventures like KDE, Ubuntu, Mozilla, et al.  So odds are I’ll bump into some of them here or there.

What I’d really like to do, though, is form a consortium of sorts from all of these passionate, talented people.  Find or create some projects, like Maemo, that fire us up again and keep us strongly connected.  The opportunities are there; Apple, Google, Facebook and Amazon haven’t solved every problem yet.

More than ever, creative solutions these days demand diversity of skills.  The landscape moves too fast, the darlings of industry overturned too often for people to successfully coagulate into homogenous, bureaucratic masses.  Those deeply embedded in the eroding status quo haven’t realized that yet.  But my old Maemo and MeeGo friends do.  They’re out there now, plowing new furrows in stale fields and causing wonderful disruption.  They’re fast refactoring MeeGo communities into new groups, some with new but related purpose.

Even with the so-called failures of Maemo and MeeGo, I’m proud of what the members accomplished.  I’m pleased to have been a part of those grand experiments.  And instead of bemoaning the outcomes, let’s refocus.  Retarget.  Identify and support initiatives that take from and extend the best parts of both.  Include rather than exclude.

Anyway, I’m not going anywhere.  I’m finding new focus.  I’ll see you all at Qt Project, in the Mer IRC channel, a local Windows Phone meetup or maybe some big conference somewhere.  Let’s stay in touch.  That’s what communities do.

Filed under: Employing Opportunity, Getting Qt, Into Outreach, Inviting Change, Mentioning Maemo, Mentioning MeeGo, Smooth Codings, The Write Stuff, Tizen Rising, Ways of Rocking Tagged: forumnokia, Intel, KDE, LinkedIn, Maemo, MeeGo, Mer, Mozilla, Nokia, Qt, Ubuntu

M-Commerce is transitioning to something new. Is this a missed opportunity for the Operators?

I just read a good summary of what’s happening with m-commerce from GigaOM.  He reports that in the US, m-commerce transactions have increased between 3 and 5 times year on year for this period running up to Christmas.  Note when people quote percentages and multiples its because the absolute numbers can still be quite low, but I think this is still very significant for a number of reasons. 

Traditionally mobile transactions have been for mobile content such as Apps and Music, but the implication is that this is changing.  With the advent of mobile checkins/location monitoring apps, the rise of the recommendation engine is becoming significant.  People are being  persuaded to use their mobile to aid the decision making or even suggest physical goods purchases.  It’s still really early days.  This morning I watched Robert Scoble interview Dennis Crowley at LeWeb.  Dennis is now putting big emphasis away from checking in for mayorships and pushing the concept of their Explorer recommendation engine – he sees this as the future of Foursquare; and so do I.  In fact I see it as the future of lots of companies.  M-commerce is in transition, whilst apps and music purchases may still dominate the transactions today, there is some evidence something new and very different is about to happen;  people are beginning to make physical goods purchases from their mobile.  I can envisage me making most of by physical goods purchase from my phones with the help of tools such as recommendation engines.

So who commercially is going to benefit from this new area.  Well, the usual suspects of Google, Twitter and Facebook are there along with the new kids on the block of Foursquare coming up quickly.  But I began thinking where are the operators?

The operators have had all the building blocks to enable such services for years.  They have identity, location and charge to bill capability.  So what are they doing?   Well I’ll leave that an open question but here’s a list of what they should be doing…

1) enabling identity everywhere (so they can recognise their users on Wifi as well as when they’re on their network) (NB this is technically possible).

2) the big operators should be working together to enable cross-operator services which work no matter which operators they are on.

3) they should be enabling commercial 3rd parties to create services which use their information, such as identity, location, charge to bill etc. 

They should be investing in these heavily because there is still time to effectively compete with Google and Facebook but that window of opportunity will disappear unless they do it now.

 

 

 

A Qt QML Beginner’s Project: MotoRing, part 2 – Rewind and Reveal

Finally, here’s the much-demanded second part to this QML beginner-focused series.  Okay, one guy asked, but he sounded really interested.

I said at the end of the first article that I would progress to the next phase in this one.  But the request for a screenshot of the app at this point got me to thinking that it would be worth more to fledgling QML developers if I backed up and broke down the code.  So let’s do it.  There’s a lot to cover, so I’ll spread it across two or three articles.

First, the promised screenshot:

MotoRing, phase 1

There’s more going on here than my final app would really need, but I was working for two things here: one, to expand the original code example’s functionality for anyone following me, and also to provide visual feedback of functionality for my own drive trials.  Ultimately, the home screen will be very simple and the app will rely on a separate configuration screen (or menu) along with notification audio and dialogs screens.  For safety’s sake, and especially given that this app is to reduce driver interruptions, emphasis will be on audio.

As you can see, I placed units selection at the top of the screen.  That made it easy to toggle back and forth between miles-per-hour and kilometers-per-hour during testing.  Speed certainly doesn’t need the level of precision shown; I should just truncate at the decimal point.  The screen above shows that typical US measurements are selected (feet, miles) and the speed shown is in miles per hour.  I could also add more context (i.e., “MPH” or “KPH” after the speed readout) but that’s not necessary for this app.

Now, let’s dig into the code, starting with main.qml, which is automatically created for Qt Quick projects.

There’s the usual basic requirements of course.  In main.qml, the “home” code, we load the necessary libraries for QT Quick and MeeGo Harmattan:

import QtQuick 1.1
import com.nokia.meego 1.0

The actual declarative code describes the home page itself:

PageStackWindow {
    id: appWindow
    initialPage: mainPage
    showStatusBar: true

    MainPage {
        id: mainPage
    }
    ToolBarLayout {
        id: commonTools
        visible: true
        parent: appWindow.pageStack.currentPage

        Item {
            id: switchRow
            width: 300
            height: 32
            anchors.verticalCenter: parent.verticalCenter

            // Switch for power saving: toggle gps on/off
            Switch {
                id: gpsSwitch
                anchors.verticalCenter: parent.verticalCenter
                checked: false
                anchors.right: parent.right
                anchors.rightMargin: 50
            }
            Text {
                id:switchText
                font.pointSize: 24
                text: gpsSwitch.checked ? "GPS ON" : "GPS OFF"
                horizontalAlignment: Text.AlignRight
                anchors.verticalCenter: parent.verticalCenter
                anchors.right: gpsSwitch.left
                anchors.rightMargin: 25
                font.family: "Nokia Pure"
            }

        }
// menu not yet implemented
        ToolIcon {
            platformIconId: "toolbar-view-menu";
        }
    }
}

I’m still struggling to fully understand how to use the PageStackWindow element (and welcome all explanations and examples) but the functionality is clear: it identifies the content page(s) to load for main.qml.  In this case, we have MainPage.qml (which is also created by default) which contains our actual program and is selected via initialPage: mainPage.  (note: I still haven’t figured out how to manage multiple pages with this, and could use some help!)

I have customized the default main.qml content by removing some of the auto-generated stuff and replacing it with what my app needs.  In this case, an on/off switch (gpsSwitch) on the Toolbar (commonTools) at the bottom of the page.  The switch works in conjunction with a text box (switchText), so both elements are grouped into an Item called switchRow. The Item element, as explained here, makes such grouping (and therefore managing) of common and/or related items easy.  As a side note, I’m sure I don’t have to explain what the id property is doing for all elements… do I?  ;)

To toggle the GPS status, we use text: gpsSwitch.checked ? “GPS ON” : “GPS OFF”. Think of this as a simple IF/THEN. When the switch is on, the text value is set to “GPS ON”.  (I’m thinking I can get rid of my two chunks of in-line JavaScript in MainPage.qml by doing something similar.)

If I understand right, showStatusBar: true makes the Toolbar visible.  You’ll also see a menu item referenced in the last code chunk.  I haven’t got to that yet, but I’m hoping I can use the popup menu for settings.

There really isn’t much to main.qml on this or must other projects I’ve looked at.  It’s my understanding that keeping the page loader simple and using individual pages for specific app features is the best practice.  Someone correct me if that’s wrong!

On a related note, while checking tour dates of musical groups I enjoy, I realized there wasn’t an event planner app for MeeGo Harmattan that would suit my purposes.  So I’ll make that another documented project, one that might actually be easier than this one.

One recurring, general gripe: I’m really perturbed by some common Qt Quick elements being documented, separately, as both Symbian and MeeGo types.  PageStackWindow is one example (note that I deliberately linked to MeeGo Harmattan documentation).  Why is this?

Next: I’ll parse out MainPage.qml…

Filed under: Getting Qt, Into Outreach, Mentioning Maemo, Mentioning MeeGo, Smooth Codings, The Write Stuff Tagged: forumnokia, GPS, LinkedIn, MotoRing, N9, N950, Nokia, QML, Qt