How to set the selecteditem

断了今生、忘了曾经 提交于 2019-12-10 19:59:52

问题


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 sets 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.

回答1:


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";



回答2:


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.




回答3:


Surely you want to set the data in the underlying datasource and then just refresh your list?



来源:https://stackoverflow.com/questions/4418754/how-to-set-the-selecteditem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!