如何设置所选项目的内容

3

我正在尝试设置Silverlight工具包中的列表选择器控件(用于Windows Phone 7)的值/选定项(当用户想要编辑XML条目时,它会从IO中提取数据并将其设置在文本框/列表选择器中)。

我目前正在尝试使用以下方法:

ListPickerSub.SelectedItem = sub;

(sub是一个字符串)

但是它抛出了一个System.InvalidOperationException异常

Additional information: SelectedItem must always be set to a valid value.

1
sub是什么?它实际上属于列表吗? - Thomas Levesque
这是存储中一个元素的值,如果我使用xElement("subElement").Value来设置数据绑定,那么sub的值就与subElement中的值相同。我还尝试过(只是为了测试)通过静态设置列表选择器的内容:sys:String星期一</sys:String> sys:String星期日</sys:String> - Jamie
3个回答

3

SelectedItem 期望一个ListPickerItem(它是列表中的一项)。你正在传递一个字符串 - 因此出现错误。

你可能会发现设置SelectedIndex更容易。

如果不知道你正在用什么来填充列表,很难给出关于如何设置SelectedItem的相关示例。

编辑:
以下是如何绑定到字符串的示例。如果没有可行的示例可以绑定到itemsource,则这是我所能做的最好的了。 (只给出对象名称或部分代码是不够的。)

假设:

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

然后我可以将内容绑定到:
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";
}

使用以下代码设置SelectedItem

ListPickerSub.SelectedItem = "sunday";

我是用以下方式填充列表的:` ` - Jamie
@Jamie,你传递的是什么ItemSource? - Matt Lacey
绑定 subName。我尝试使用:object index = SubTxt.FindName(sub); 然后将 selecteditem 设置为 index,但 index 总是返回 null。 - Jamie
非常感谢,它完美地工作了。我遇到的唯一问题是在我的设置中,我像这样设置了列表选择器: <sys:string>星期一</sys:string> 对于每个值,与我所有的设置一样,我使用了双向绑定来设置所选项目:SelectedItem="{Binding Source={StaticResource AppSettings}, Path=WeekBeginsSetting, Mode=TwoWay}这个绑定返回了正确的值,因为我已经用它来设置文本块的文本(只是为了测试)。但是当尝试设置所选项目时,它会抛出一个 System.ArgumentOutOfRangeException - Jamie
@Jamie 请将这个新问题作为一个新的问题来提出。如果你能发布一个完整的示例来演示问题,这将有助于更快、更相关地获得答案。另请参阅http://stackoverflow.com/faq#howtoask。 - Matt Lacey

2

类似以下内容:

ListPickerSub.SelectedItem = ListPickerSub.Items.First(x => (x as ListPickerItem).Content.ToString() == sub);

您可能需要将Content转换为TextBlock,并相应地更改代码。以上代码适用于我的情况,其中ListPicker使用ListPickerItem动态填充。


0

你肯定想要在底层数据源中设置数据,然后只需刷新列表即可吧?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接