开发者

Change ListBox's selected Item in Windows phone 7

I need to select an item from a list box that contains objects of my class. Here is my code:

the load event:

  private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
  {
      XDocument loadedData = XDocument.Load("file.xml");
      var data = from query in loadedData.Descendants("element")
                 select new myClass
                 {
                     First = (string)query.Element("first"),
                     Second = (string) query.Element("second")
                 };
      List<myClass> d = data.ToList<myClass>();
      myList = d; 
      myListBox.ItemsSource = data;            
  }

and then my button which is supposed to change the selected Item:

  private void button1_Click(object sender, RoutedEventArgs e)
  {
      myListBox.SelectedItem = myList[100];
  }

开发者_StackOverflowam I doing something wrong here?


myList isn't the collection you've bound to the list.
Either make d a wider scoped variable and refer to that in button1_click
or
store data in myList rather than a copy of it.


For efficiency, I would set the ItemsSource to 'd' rather than 'data'. The enumeration returned by the linq query is lazy, so it gets evaluated every time the UI updates. The array you have is eagerly created, so later lookups are fast.


Looks like a little bug here. I was able to inconstantly replicate a similar problem.

I used the standard VS template for a Databound Application. The template comes with some sample data and a populated list box. I added a button which set the selected item to the 15th item in the collection. This worked as expected. However, when I scrolled the list up to the top it wouldn't return to the 15th record when I clicked the button. Taking a guess here, what you're running into is another symptom of the same problem.

To solve this I first set the SelectedIndex to -1 which essentially deselects the item.

private void button1_Click(object sender, RoutedEventArgs e)
{
    myListBox.SelectedIndex = -1;
    myListBox.SelectedItem = myList[100];
}

I'm curious if this also solves your problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜