How to set the selecteditem
I am trying to set the value/selecteditem of a listpicker control - from the silverlight toolkit for windows phone 7 (when the user wants to edit an entry in xml, it pulls the data out of IO and 开发者_StackOverflowsets it in the text boxes/listpickers).
I am currently trying to use:
ListPickerSub.SelectedItem = sub;
(sub is a string)
But it is throwing a System.InvalidOperationException
Additional information: SelectedItem must always be set to a valid value.
SelectedItem
is expecting a ListPickerItem (which is one of the items in the list). You're passing it a string - hence the error.
You may find it easier to set the SelectedIndex
.
It's hard to give a relevant example of setting the SelectedItem without knowing what you're populating the list with.
Edit:
Here's an example of how you could bind to strings. Without a workable example of what you are actually binding to the itemsource this is hte best I can do. (Just giving the name of the object or partial code isn't enough.)
Assuming:
<Controls:ListPicker x:Name="ListPickerSub">
<Controls:ListPicker.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</Controls:ListPicker.ItemTemplate>
<Controls:ListPicker.FullModeItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</Controls:ListPicker.FullModeItemTemplate>
</Controls:ListPicker>
Then I can bind the contents with:
ListPickerSub.ItemsSource = SubItems();
private IEnumerable<string> SubItems()
{
yield return "monday";
yield return "tuesday";
yield return "wednesday";
yield return "thursday";
yield return "friday";
yield return "saturday";
yield return "sunday";
}
and set the SelectedItem
with:
ListPickerSub.SelectedItem = "sunday";
Something like the following:
ListPickerSub.SelectedItem = ListPickerSub.Items.First(x => (x as ListPickerItem).Content.ToString() == sub);
You may need to cast the Content to TextBlock, and change the code accordingly. The above works for my case where ListPicker is populated dynamically using ListPickerItem.
Surely you want to set the data in the underlying datasource and then just refresh your list?
精彩评论