Make the ListPicker or RadListPicker behave in a ScrollViewer

I’ve seen a lot of applications that have a page in there that just doesn’t behave the way it should. Either there’s a textbox that’s placed in a not so brilliant way, where a lot of controls are covered by the onscreen keyboard and there’s not a nice way to close the keyboard (tapping somewhere on the screen is not a nice way, is it?). The same goes for ListPickers, when they are placed in a ScrollViewer at the bottom of the screen chances are that you’re only seeing one item once you open de ListPicker, the rest is at the bottom of the screen.

A picture is worth a thousand words, so here the situation of the ListPicker I’m explaining, closed (no trouble) and opened where the user hardly sees that there are options at all.

closed

opened wrong

 

 

 

 

 

 

 

 

Of course I want to fix this. And I even know I fixed this before, but I had to think hard in which app I fixed this problem. I found the code but in the old app I was making use of the ListPicker from the Windows Phone Toolkit and now I’m making use of the RadListPicker by Telerik. Though besides that I didn’t find anyone blogging about this before. That’s why I’m writing this. The code I show in here could have been written by someone else, but I can’t remember.

ListPicker from the Windows Phone Toolkit solution

The original ListPicker can react to the GotFocus event to then bind to the SizeChanged event in which the actual logic for making the control visible in the scrollviewer is called. The magic piece is shown in the end, it’s shared by both solutions. The magic is in line 8 of course.

NewTracksToDownloadPicker.GotFocus += PickerGotFocus;

private void PickerGotFocus(object sender, RoutedEventArgs eventArgs)
{
    var picker = sender as ListPicker;
    if (picker != null)
    {
        picker.SizeChanged += (s, e) => picker.EnsureVisibleInScrollViewer();
    }
}

RadListPicker by Telerik solution

The RadListPicker by Telerik doesn’t fire the GotFocus event at the same time, so I had to pick and try to correct event to listen to. I found out that the StateChanged event works best for me.

NewTracksToDownloadPicker.StateChanged += PickerStateChanged;

private void PickerStateChanged(object sender, ListPickerStateChangedEventArgs listPickerStateChangedEventArgs)
{
    var picker = sender as RadListPicker;
    if (picker != null)
    {
        picker.SizeChanged += (s, e) => picker.EnsureVisibleInScrollViewer();
    }
}

 

So now it’s time for some magic!

No not really, but the code can be quite handy for other situations as well when you want to be sure a control is completely visible inside a ScrollViewer.

The magic consists of two parts, finding the parent ScrollViewer of the Control you want to make visible. With all kinds of nesting, it could be difficult to tell how many levels are there. So with the help of the VisualTreeHelper and a little bit of recursion you get this pieces of code.

public static T FindParentOf<T>(this UIElement element) where T : UIElement
{
    var found = FindParentOf(element, typeof(T)) as T;
    return found;
}

public static DependencyObject FindParentOf(DependencyObject element, Type type)
{
    if (type.IsInstanceOfType(element))
        return element;
    DependencyObject parent = VisualTreeHelper.GetParent(element);
    if (parent == null)
        return null;
    return FindParentOf(parent, type);
}

 

So that piece of magic is gone. Next is the actual making sure that the control is visible in the ScrollViewer. A little bit of measuring and making the ScrollViewer to scroll to the measured position. What magic were you talking about?

public static void EnsureVisible(this ScrollViewer scroller, UIElement element)
{
    scroller.UpdateLayout();

    double maxScrollPos = scroller.ExtentHeight - scroller.ViewportHeight;
    double scrollPos =
        scroller.VerticalOffset -
        scroller.TransformToVisual(element).Transform(new Point(0, 0)).Y;

    if (scrollPos > maxScrollPos) scrollPos = maxScrollPos;
    else if (scrollPos < 0) scrollPos = 0;

    scroller.ScrollToVerticalOffset(scrollPos);
}

public static void EnsureVisibleInScrollViewer(this UIElement element)
{
    var scrollViewer = element.FindParentOf<ScrollViewer>();
    if (scrollViewer != null)
        scrollViewer.EnsureVisible(element);
}

 

Yes, I know you want to see the end result. Have fun with it!

opened correctly
  • Gravatar Cialis May 8th, 2014 at 03:12
    I've learn a few good stuff here. Certainly value bookmarking for revisiting.
    I surprise how a lot effort you put to create this sort of excellent informative site.
  • Gravatar mulberry sale May 8th, 2014 at 04:49
    The hoodie is 51 percent rayon, 37 percent cotton and 12 percent polyester and is machine washable.
  • Gravatar mulberry 氓rhus May 19th, 2014 at 07:05
    Det er ikke f酶rste gang, at modellen har stillet for det britiske m忙rke, hun var ogs氓 over for deres AW13 kampagne og gik i deres SS14 show p氓 London Fashion Week.
  • Gravatar New Ninja Cheap May 19th, 2014 at 11:50
    Excellent service, fast shipping, top rate product
  • Gravatar 2935 May 29th, 2014 at 14:59
    Thanks so much, a little grand daughter will be very happy. Very fast shipping.
  • Gravatar salvajor garbage disposal June 7th, 2014 at 16:59
    This is really interesting, You're a very skilled blogger.
    I've joined your rss feed and look forward to seeking more of your magnificent post.

    Also, I have shared your web site in my social networks!
  • Gravatar Tachi Katana June 9th, 2014 at 12:31
    Perfect, thanks so much!
  • Gravatar Replica Miu Miu Bags australia June 9th, 2014 at 16:19
    Great celine shoe. Excellent condition.
  • Gravatar mbt shoes uk ebay June 18th, 2014 at 07:38
    mbt shoes zalika Make the ListPicker or RadListPicker behave in a ScrollViewer - Silverlight, WP7, .NET, C#, ASP.NET MVC
  • Window shopping for Authentic nfl Jerseys, China Authentic nfl Jerseys wholesale supply mall.
  • Gravatar japanese naginata sword June 25th, 2014 at 04:28
    About three Top rated Tactics As used by Affiliates To achieve success _disibledevent="">There are methods which may have proved helpful before with online marketing and that remain powerful from the online internet affiliate marketing world currently. With these circus tent three marketing methods, it will be possible to enhance your sales and also make it from the internet affiliate marketing company.<br /><br />The three practices are as follows.<br /><br />one. Employing alone(p) web pages in promoting to each one freestanding product or service you are marketing. Tend not to ball the whole thing unitedly just to save some dough on internet web host. It is advisable to possess particular person web-sites focusing on just about every product or service and nothing in addition. <br /><br />Constantly incorporate product reviews one specific thus website visitors could have a great overture knowledge of exactly what the product or service is capable of for those who buy it. Furthermore incorporate testimonials from buyers with previously ordered the product or service. Follow distinct in mind these buyers are more when compared with prepared to permit you to to utilize their own companies and also pictures one specific with the presumption consequence you are marketing. <br /><br />You are able to moreover prepare articles or blog posts conveying this utility with the product or service and include all of them on the spot as an second page. Make websites magic, compelling and include message or calls to act around the data. Each and every headline ought to fascinate your readers to try to find out more, possibly at the-postal mail a person. Highlighting your " special " things. This will help to your readers to make sure exactly what the page is around all of which will desire to learn come out additionally.<br /><br />only two. Supply cost-free accounts for your visitors. In case workable locate them around the top part of your current page so they just can't be skipped. Make an effort to produce autoresponder announcements that'll be mail-clad to opportunity seekers whom enter their particular data into your current enroll package. In line with study, an arrangement is definitely shut often around the 7th contact with a prospect.<br /><br />Simply just two things tin perchance arrived at cross while using the web page alone: Closed down sale or prospect making this page and never coming back over again. Through transmitting informatory data to their computer mail at a number of given stages, you might advise all of them with the product or service these people thinking these people wanted later all of which will discover that the sale is definitely shut. Be assured that this content is definitely given to correct reasons why you should get the product or service. Tend not to pass find like a pitch. <br /><br />Concentrate on prestigious things similar exactly how your current detail can make lifestyle and also factors easier and even more pleasurable. Consist of compelling theme outlines from the electronic mail. Wherever possible, stay clear of when using the expression 閿熸枻鎷穥free|totally free|free of charge|no cost|cost-free|loose}閿熸枻鎷?as there are however aged junk e-mail filter systems which dump those people varieties of written content to the unhealthy before possibly a person scans all of them foremost. Convince folks who decided upon your current no cost accounts that they will be dropping a thing critical whenever they do not take on good thing about your products and also providers.<br /><br />a few. Purchase the style of visitors that may be relevant to your current detail. Just think, when the individual who frequented your website has 0 pastime in the least within what you will be showing, they will be among folks who get over it and never return. Create articles or blog posts pertaining to launch within at the-zines and also at the-accounts. Using this method you will find journals while using the intent behind consentrate on your current target audience and also what you possess can could sketch their own attention.<br /><br />Make an effort to prepare at the very least only two articles or blog posts per week, with at least three hundred-six-hundred text in total. Through consistently creating tweaking these postings you can generate as much as a hundred targeted visitors to your site each day. <br />Try to remember which simply one out of a hundred website visitors are likely to get your product or service or obtain the services you provide. If you can create up to one,000 targeted gets on your internet site within a day time, that means you can accomplish 10 sales in line with the run of the mill statistic. <br /><br />The particular methods presumption previously mentioned will not actually audio very hard to accomplish, if you think maybe over it. It really uses a almost no time and also an action plan by you. <br /><br />Make an effort to utilize the following tips for several associate degree marketing packages. You are able to turn out keeping a good source of gross and also make it in this company that doesn't many internet marketers is capable of. Moreover, think of the substantial paychecks you will end up having閿熸枻鎷?/p>
  • Gravatar New Prada Shoulder Bag UK For Cheap June 26th, 2014 at 07:20
    Very quick shipping, item exactly as described! Thank you!
  • Gravatar Emory July 18th, 2014 at 15:18
    Wonderful blog! Do you have any hints for aspiring
    writers? I'm hoping to start my own website soon but I'm a little lost
    on everything. Would you propose starting with a free
    platform like Wordpress or go for a paid option? There are so many choices out there
    that I'm completely overwhelmed .. Any suggestions?
    Thanks!
  • Gravatar Naginata July 19th, 2014 at 22:13
    Grande , merci!
  • Gravatar stivali donna timberland July 24th, 2014 at 03:59
    Shoppers will board the Red Line at Jackson, Monroe, Washington, and Lake streets underneath this major thoroughfare. Tourists should simply walk to State Street to take the Red Line and avoid confusion. Locals, mindful of the cyclical patterns of the various lines that traverse the Loop will be able to enter the CTA system from several platforms and transfer to the Red Line at State and Lake.
  • Gravatar Rayford August 16th, 2014 at 03:46
    Excellent beat ! I would like to apprentice while you amend your site, how can i subscribe for a blog site?
    The account helped me a acceptable deal. I
    had been a little bit acquainted of this your
    broadcast provided bright clear idea
  • Gravatar New Parajumpers Right Hand Men Jackets Sale September 3rd, 2014 at 02:13
    exactly as described! Thanks so much! Excellent seller!
  • Gravatar vlogging equipment September 3rd, 2014 at 22:33
    Great blog! Do you have any tips and hints for aspiring writers?
    I'm planning to start my own website soon but I'm a little lost on everything.
    Would you propose starting with a free platform like
    Wordpress or go for a paid option? There are so many choices out there that I'm totally overwhelmed
    .. Any recommendations? Thanks a lot!
  • Gravatar karlymarkus58.jigsy.com September 6th, 2014 at 08:36
    This is really attention-grabbing, You're an excessively skilled blogger.
    I've joined your feed and stay up for looking for more
    of your fantastic post. Additionally, I have shared your web site in my social networks
  • Gravatar Battle ready Swords September 8th, 2014 at 02:34
    Opération facile. Parfait état . Expédition rapide. Hautement recommandé !
  • Gravatar レイバン 人気 直営店 September 26th, 2014 at 06:01
     Wan Yun inclusion from what? Betty assistant meetings can consider On the internet train handbags dismissed immediately after a few months to move.<br> Ignore regarding ** China and taiwan to help have confidence in! On the internet train handbags Ought to analyze your frame of mind of your Chinese language folks,|enjoy|all the best|peace of mind|all the best !
  • Gravatar Organisational Resilience November 6th, 2014 at 02:15
    Aw, thhis was a really nice post. Takihg the time and actual effdort to make a suuperb article… but what can I say… I
    procrastinate a whole lot and don't seem to get anythinmg done.
  • Gravatar http://tinyurl.com/os3qu74 November 24th, 2014 at 05:31
    The complete body appears definitely good and so perfect.
    That includes front flap closure, it has a shiny golden padlock decorate it.
    Also handles woven as a result of the golden grommets will make the body gatherable.
    Even though it trendy for my personalized liking, it
    is absolutely an appealing glimpse really.
    It mentioned that there are only 50 ostrich and canvas
    Jamais designer purses obtainable. Even they would commit you significantly income.

    Do you even now want to very own this sort of a
    important purses? Many thanks for the replica handbags, far more and additional individuals can love the luxury vogue through buying superior high-quality replicas.

    Tags: exacthandbag, idolreplicas, replica, replica handbag,
    duplicate purses, replicas.
  • Gravatar jPClTQoxiS December 5th, 2014 at 18:24
    <a href= http://artandmobile.com/orderxanax/>xanax antidepressant</a> cheap xanax + forum - generic xanax photos
  • Gravatar ルイヴィトン バッグ コピー December 6th, 2014 at 04:45
    Their part in order to burst the leading Japanese people terrain soldiers left out for Myanmar the|and also|and then the|as well as} Indians. the number of men and women near you have got this particular unlikely notion? once the intake of many big combat, japan don't expect to have On line discipline purses and handbags cleverness providers would most likely find out meant for their self front side.
  • Gravatar Teamwork Development December 21st, 2014 at 08:22
    Excellent post. Iwas checking constantly this blogg and I'm impressed!
    Extremely helpful info particularly the last part
    :) I care for such information a lot. I was looking for this certain information for a very long time.
    Thank you and best of luck.
  • Gravatar DBwfRmheYe February 1st, 2015 at 00:37
    <a href= http://grapeescapes.net/tramadol/>buy tramadolВ overnight cod</a> tramadol 50 mg strength - tramadol withdrawal management
  • Gravatar http://pix.ie/makkeinboris February 1st, 2015 at 10:40
    I got this web page from my buddy who informed me concerning this website and at the moment this time
    I am browsing this site and reading very informative articles or reviews at this place.
  • Gravatar Tim May 15th, 2015 at 05:51
    It's actually a great and helpful piece of info. I am glad that you shared this helpful info with us.
    Please stay us informed like this. Thanks for sharing.
  • Gravatar Richardmics May 20th, 2015 at 01:18
    http://expoforseniors.com/homework/essay-for-college-magazine Essay for college magazine http://expoforseniors.com/homework/to-kill-a-mockingbird-analysis-essay To kill a mockingbird analysis essay http://comeplaynow.com/50-essays-portable-anthology 50 essays portable anthology http://comeplaynow.com/phd-thesis-writing-services Phd thesis writing services http://expoforseniors.com/homework/sentence-with-antagonist Sentence with antagonist http://goodshepherdcampus.org/homework/do-my-assiment-paper-for-me-online Do my assiment paper for me online http://comeplaynow.com/write-my-essay-custom-writing Write my essay custom writing http://defiant.cc.s170003.gridserver.com/homework/parent-essays-for-high-school-applications Parent essays for high school applications http://expoforseniors.com/homework/homework-help-online-phschool.com Homework help online phschool.com http://goodshepherdcampus.org/homework/essay-on-stress Essay on stress http://expoforseniors.com/homework/help-on-thesis-statement Help on thesis statement http://dreamtrendy.com/essay-for-scholarship-nursing Essay for scholarship nursing http://goodshepherdcampus.org/homework/how-to-write-a-essay How to write a essay http://dreamtrendy.com/financial-assignment-help Financial assignment help http://dreamtrendy.com/essaywriting-service Essaywriting service http://dreamtrendy.com/analytical-research-paper Analytical research paper http://vredescafe.eu/homework/will-writing-uk Will writing uk http://expoforseniors.com/homework/my-admission-essay My admission essay http://expoforseniors.com/homework/help-writing-descriptive-essays Help writing descriptive essays http://dreamtrendy.com/motivational-quotes-for-studying Motivational quotes for studying http://dreamtrendy.com/discovery-education-website Discovery education website
  • Gravatar Richardmics May 24th, 2015 at 22:50
    http://aureumevents.co.uk/essay/ghostwriting-service-page.pdf Ghostwriting service page http://aureumevents.co.uk/essay/animal-abuse-persuasive-essay.pdf Animal abuse persuasive essay http://aureumevents.co.uk/essay/uk-best-essays.pdf Uk best essays http://cdspub.com/batb/dissertation/reasons-to-go-to-college-essay Reasons to go to college essay http://aureumevents.co.uk/essay/science-games-for-high-school.pdf Science games for high school http://cdspub.com/batb/dissertation/racial-discrimination-research-paper Racial discrimination research paper http://aureumevents.co.uk/essay/custom-uk-dissertation.pdf Custom uk dissertation http://aureumevents.co.uk/essay/do-my-essay-uk.pdf Do my essay uk http://bagdays.com/papers/college-essays-for-sale-california-southern College essays for sale california southern http://cdspub.com/batb/dissertation/buy-research-paper-now Buy research paper now http://bagdays.com/papers/english-essays-for-o\'level-students English essays for o\'level students http://bagdays.com/papers/wrtting-essays Wrtting essays http://aureumevents.co.uk/essay/community-service-nursing-home-essay.pdf Community service nursing home essay http://bagdays.com/papers/why-do-you-want-to-be-a-teacher-essay Why do you want to be a teacher essay http://aureumevents.co.uk/essay/help-me-with-my-statistics-homework.pdf Help me with my statistics homework http://avancados.info/essay/paper-grading Paper grading http://avancados.info/essay/essay-type-resume Essay type resume http://cdspub.com/batb/dissertation/last-paragraph-of-an-essay Last paragraph of an essay http://avancados.info/essay/homework-hotline-com Homework hotline com http://cdspub.com/batb/dissertation/do-assignment-for-money Do assignment for money http://cdspub.com/batb/dissertation/collection-of-essays Collection of essays
  • Gravatar men hoodies October 23rd, 2015 at 17:40
    It was also arguably an early predecessor of Instagram's #freethenipple movement — and
    the altering attitudes (and laws) about toplessness in the latter half of the century.
  • Gravatar Minions Paradise Hack sand dollars November 13th, 2015 at 13:56
    This Minions Paradise Hack Software has been created by the
    specialists with a view to help players and don't pose a risk to
    your account.
  • Gravatar Städning Göteborg December 3rd, 2015 at 10:47
    I don't know if it's just me or if everybody else experiencing
    issues with your website. It appears as though some of the text on your content are running off the screen. Can somebody else please provide feedback and let me know if this is
    happening to them as well? This may be a issue with my browser because I've
    had this happen previously. Many thanks
  • Gravatar Naginata December 4th, 2015 at 11:13
    EXCELLENT SELLER!! Love the shoe and great communication!!! A+++++
  • Gravatar Tachi Sword December 4th, 2015 at 11:13
    Easy transaction. Perfect condition. Fast shipping. Highly recommended!
  • Gravatar Jas Pengantin Pria December 10th, 2015 at 17:44
    It's really very complicated in this busy life to listen news on Television,
    so I only use world wide web for that reason, and get
    the most recent information.
Gravatar