• 0

WP8 / c# List.ItemsSource completed


Question

I am making a Windows Phone app and I need to select some of the items loading in the list.  I'm looping through some XML and adding them to a list

var TransitList = new List<string>();

//loop through XML here

BATList.ItemsSource = TransitList;

This works fine, however after this line I am attempting to set some of the item as selected

                SolidColorBrush brushSelected = new SolidColorBrush(Color.FromArgb(255, 190, 190, 190));

                for (int i = 0; i < this.BATList.Items.Count; i++)
                {
                    ListBoxItem BATListItem = (ListBoxItem)(this.BATList.ItemContainerGenerator.ContainerFromIndex(i));
                    BATListItem.IsSelected = true;
                    BATListItem.Background = brushSelected;
                }  

However each item is coming up as null.  If the code is placed elsewhere an manually run (obviously not an option) the values are not null and the process runs correctly. 

So, I need one of two things to happen:

* I need an event to fire when the ItemsSource is completed

* A way to add values to the list that can be selected (obviously a string list wont do)

 

Thoughts?

 

 

Link to comment
Share on other sites

2 answers to this question

Recommended Posts

  • 0

            var list = new List<String> { "Cheese", "Hello", "Apples", "Fish" };

            lb.ItemsSource = list;
            lb.SelectionMode = SelectionMode.Multiple;
            lb.SelectedItems.Add(list[0]);
            lb.SelectedItems.Add(list[2]);
That does the job for me, using a bog standard ListBox

 

<ListBox x:Name="lb" />
You could, and probably should set the SelectionMode in XAML though :p

 

 

(The default ItemsContainer style for a ListBox overwrites the foreground colour of each ListBoxItem to the phones Accent colour - using Visual States -  when it / it's child becomes selected, which is why this works. It'll usually be easier to work with Visual States or change properties through binding converters rather than messing directly with trying to manipulate individual visual elements through code )

Ergo, to change the colour, you'd have to overwrite the default ItemsContainerStyle. Using Blend (or Visual Studio), you can right click on your ListBox in design time view, Click "Edit Additional Templates", click "Edit ItemsContainerStyle", store the resource somewhere and then look the XAML for the container style - you'll see a selected visual state that changes the foreground colour - you just stick your own colour in there.

Link to comment
Share on other sites

This topic is now closed to further replies.