12Apr/122

Fixing the LongListSelector part 2: Making the SelectedItem bindable.

One of the problems of the LongListSelector in the current release of the Silverlight for Windows Phone Toolkit comes to the surface in MVVM scenarios. You often bind the SelectedItem to some property on the viewmodel so you can have access to the selected item. This works fine for a ListBox, but on the LongListSelector it doesn't work.

The problem is that the SelectedItem property on the LongListSelector is not a dependency property, and is therefore not bindable. The solution to this problem is of course to change it to a dependency property. But if you don't want to change the source and recompile there is also another way to add this.

The following piece of code creates a new control which inherits from the normal LongListSelector.

- It adds a new dependency property called SelectedItem and hides the SelectedItem property of the base class by using the "new" modifier.

- It explicitly sets the SelectedItem dependency property when the selection changes, which in fact comes down to syncing the dependency property with the  SelectedItem property of  the base class.

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

If you are going to recompile the toolkit, than don't forget to get the latest sources from codeplex. There are some new fixes checked in in the past few days.

If you have any question regarding this blog post or another related thing, feel free to contact me via the comments, the contact form or twitter.

Did you like this? Share it:
Tagged as: , , 2 Comments