chobo2
chobo2

Reputation: 85775

How to unselect selected row in LongListSelector in WP8

I must say that I really dislike the LongListSelector in WP8 and like the toolkit version so much better.

First it is not MVVM compatible so I found this code to make it so.

  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); }
        }
    }

then I made a view model using mvvm light

  public class MainViewModel : ViewModelBase
    {

        public MainViewModel()
        {
           MyList = new ObservableCollection<Test>
           {
               new Test
               {
                    Name = "test 1"
               },
               new Test
               {
                   Name = "test 2"
               }
           };

           ButtonCmd = new RelayCommand(() => Hit());
        }

        private void Hit()
        {
            SelectedItem = null;
        }

        public ObservableCollection<Test> MyList { get; set; }

        /// <summary>
        /// The <see cref="SelectedItem" /> property's name.
        /// </summary>
        public const string SelectedItemPropertyName = "SelectedItem";

        private Test selectedItem = null;

        /// <summary>
        /// Sets and gets the SelectedItem property.
        /// Changes to that property's value raise the PropertyChanged event. 
        /// </summary>
        public Test SelectedItem
        {
            get
            {
                return selectedItem;
            }

            set
            {
                if (value != null)
                {
                    MessageBox.Show(value.Name);
                }


                if (selectedItem == value)
                {
                    return;
                }

                RaisePropertyChanging(() => SelectedItem);
                selectedItem = value;
                RaisePropertyChanged(() => SelectedItem);
            }
        }


        public RelayCommand ButtonCmd
        {
            get;
            private set;
        }

then I made a model

public class Test : ObservableObject
    {
        public string Name { get; set; }
    }

then I made the xaml

<phone:PhoneApplicationPage
                            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                            xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
                            xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
                            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                            xmlns:ignore="http://www.ignore.com"
                            xmlns:local="clr-namespace:MvvmLight2" x:Class="MvvmLight2.MainPage"
                            mc:Ignorable="d ignore"
                            FontFamily="{StaticResource PhoneFontFamilyNormal}"
                            FontSize="{StaticResource PhoneFontSizeNormal}"
                            Foreground="{StaticResource PhoneForegroundBrush}"
                            SupportedOrientations="Portrait"
                            Orientation="Portrait"
                            shell:SystemTray.IsVisible="True"
                            DataContext="{Binding Main, Source={StaticResource Locator}}">

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot"
        Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <local:LongListSelector ItemsSource="{Binding MyList}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}">
            <local:LongListSelector.Resources>
                <DataTemplate x:Key="ItemTemplate">
                    <Grid>
                        <TextBlock Text="{Binding Name}" HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="48"/>
                    </Grid>
                </DataTemplate>
            </local:LongListSelector.Resources>
            <local:LongListSelector.ItemTemplate>
                <StaticResource ResourceKey="ItemTemplate"/>
            </local:LongListSelector.ItemTemplate>
        </local:LongListSelector>
        <Button Content="Unselect" HorizontalAlignment="Left" Margin="142,81,0,0" Grid.Row="1" VerticalAlignment="Top" Command="{Binding ButtonCmd, Mode=OneWay}"/>
    </Grid>

</phone:PhoneApplicationPage>

when I click on the first item in the list, the message box shows up, if I hit it again nothing happens. I then hit my button which nulls out the selectedItem(which in the old toolkit version would be enough) and try again and nothing happens.

Only way I can every select the first row is by selecting the second row which is really bad if say the list only has 1 item at any given time.

Weird thing is that a simple collection of strings does not even require me to set the SelectItem to null as it always seems to deselect but when it comes to complex types it is a no go.

Upvotes: 0

Views: 541

Answers (2)

robert_enough
robert_enough

Reputation: 371

I've used the same code and ran into the very same problem. Reason for it is that your SelectedItem property overshadows the base.SelectedItem property. When setting it to a new value, not only set your SelectedItem property but the base one as well:

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

Then you have a MVVM capable code and can reset the SelectedItem in your ViewModel as well (by setting it to null).

Upvotes: 1

techloverr
techloverr

Reputation: 2617

you can easily achieve via in selectionchanged event

void LongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if((sender as LongListSelector).SelectedItem == null){

             return;
            }

            SelectedItem = base.SelectedItem;
            (sender as LongListSelector).SelectedItem = null;   
        }

Upvotes: 0

Related Questions