Klaus Nji
Klaus Nji

Reputation: 18847

Manually selecting ListBoxItem

I need to be able to manually select ListBox items in Windows Phone 7. My ListBox contains the following style that uses a WrapPanel

   <Style TargetType="ListBox">
                        <Setter Property="ItemsPanel">
                            <Setter.Value>
                                <ItemsPanelTemplate>
                                    <[WP7Panels:WrapPanel][2] />
                                </ItemsPanelTemplate>
                            </Setter.Value>
                        </Setter>
                        <Setter  Property="ScrollViewer.HorizontalScrollBarVisibility"  Value="Disabled"  />
                    </Style>

so that I can realize the wrapping effect.

When I did this in WPF, I subscribed to ListBox.ItemContainerGenerator.StatusChanged event. In the event handler for this event, I used:

var obj = ListBox.ItemContainerGenerator.ContainerForItem(objInstance) as ListBoxItem; if (obj != null) { obj.IsSelected= true; }

I tried doing the same thing for WP7 and noticed that:

  1. ListBox.ItemContainerGenerator no longer exposes StatusChanged event. There is instead an ItemsChanged event, so I handled this instead.
  2. However, when I call ItemContainerGenerator.ContainerForitem(objInstance) or even ItemContainerGenerator.ContainerFromIndex(), I get always get null.

Just to add, I have overriden GetHashCode and Equals on the class which is being presented in the list box.

Ideas please.

Upvotes: 0

Views: 235

Answers (1)

mostruash
mostruash

Reputation: 4189

I'm not sure if this is the best way of doing this but here is how I would do it:

1) Create a class which inherits INotifyPropertyChanged interface (You can find how to use it easily via google). Wrap your information that you put into your ListBox in that class.

2) Create a IsSelected property for that class.

3) Bind IsSelected property of the class to the IsSelected property of ListBox's items.

4) Now you can just change IsSelected property of the class that you had created whenever you want and everything happens itself.

Upvotes: 1

Related Questions