Samstag, 24. November 2012

Windows Phone 8–LongListSelector SelectedItem not bindable

Microsoft has now moved the LongListSelector to the basic phone controls, but the LongListSelector control has still the same issue as it was part of the Windows Phone Toolkit. They have forgotten to declare a DependencyObject for the SelectedItem property so you can not bind the SelectedItem property. Or maybe they want to be compatible with this bug :-)

To resolve this I decided in my current project to define a new class LongListSelector in my project namespace which is derived from the LongListSelector control. Here I can define a dependency property and a LongListSelector_SelectionChanged method to handle the binding. It is is important to declare the property in the new class as New, because we want to override the SelectedItem property in the Microsoft control.

Here is my code to do this:

public class LongListSelector : Microsoft.Phone.Controls.LongListSelector
    {
        public LongListSelector()
        {
            SelectionChanged += LongListSelector_SelectionChanged;
        }

        void LongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SelectedItem = base.SelectedItem;
        }

        public static readonly DependencyProperty SelectedItemProperty =
            DependencyProperty.Register(
                "SelectedItem",
                typeof(object),
                typeof(LongListSelector),
                new PropertyMetadata(null, OnSelectedItemChanged)
            );

        private static void OnSelectedItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var selector = (LongListSelector)d;
            selector.SelectedItem = e.NewValue;
        }

        public new object SelectedItem
        {
            get { return GetValue(SelectedItemProperty); }
            set { SetValue(SelectedItemProperty, value); }
        }
    }

4 Kommentare:

  1. If I use this solution and two-way bind the SelectedItem to an item in a ViewModel, setting the item to null in the ViewModel does not affect the SelectedItem property, i.e. there is no way to reset the SelectedItem. Is there a way to do this?

    AntwortenLöschen
  2. Here is the solution to your problem :

    http://stackoverflow.com/questions/15232725/wp8-longlistselector-selecteditem-not-bindable

    AntwortenLöschen
  3. The twitter application showing is marvelous.. I have a little mistrust with respect to Google login in my wp7 application can u please help out with it? The issue is that am fit to login to Google account through my application... at the same time am not accepting the User Id from Google..is there anything specific that i will do to accept the client id?iPhone app builder // iphone applications // Android application development

    AntwortenLöschen