带有DataTemplate的ListPicker的SelectedIndex或SelectedItem

时间:2014-09-06 06:52:16

标签: c# windows-phone-8 invalidoperationexception selectedindex listpicker

我使用Listpicker来允许用户选择颜色。 所以我使用了一个Toolkit Listpicker和一个DataTemplate,它包含Textbox来显示它的列表项。我想要的是当页面加载时,自动选择先前选择的颜色(项目)。但它给了我一个明显的System.InvalidOperationException'异常,因为项目不是简单地添加,而是通过datatemplate文本框。请帮帮我:


 <toolkit:ListPicker x:Name="BackgroundColor"  FullModeHeader="Select Background Color:" Header="Background Color:" BorderThickness="0" FullModeItemTemplate="{StaticResource PickerFullModeItemTemplate}" ItemTemplate="{StaticResource PickerItemTemplate}" Background="#FF09043C" SelectionChanged="BackgroundColor_SelectionChanged" >

           </toolkit:ListPicker>

             <phone:PhoneApplicationPage.Resources>
    <DataTemplate x:Name="PickerItemTemplate">
        <TextBlock Text="{Binding BackGroundColorString}" />
    </DataTemplate>

    <DataTemplate x:Name="PickerFullModeItemTemplate" >
        <Grid x:Name="rootGrid" Margin="0">

            <StackPanel Orientation="Horizontal">
                <TextBlock Name="BackgroundColor" 
                   Text="{Binding BackGroundColorString}"
                          />
            </StackPanel>
        </Grid>
    </DataTemplate>
                     </phone:PhoneApplicationPage.Resources>

if (SunderGutkaSettings.Contains(SG_KEY_BACKGROUNDCOLOR)) //check if key is not present, read value  
        {
            if (BackGroundColorList.Count != 0)//test if list if not empty
            {

                var ListPickerBackGroundColorRead = BackGroundColorList[singletonInstance.SelectedFontColorIndex] as BackGroundlistPickerClass; //pull whole class

                string ListPickerBackGroundColorReadString = ListPickerBackGroundColorRead.BackGroundColorString;

                int ListPickerBackGroundColorReadStringToIndex = BackGroundColorList.FindIndex(x => x.BackGroundColorString.StartsWith(ListPickerBackGroundColorReadString));

                BackgroundColor.SelectedIndex = ListPickerBackGroundColorReadStringToIndex; //DISABLE FOR testing                    


            }

实际上,在简单地编写代码时: BackgroundColor.SelectedIndex = 0;不起作用 也没有  BackgroundColor.SelectedItem =&#34;红色&#34 ;;

帮帮我

1 个答案:

答案 0 :(得分:0)

设置项目

This.BackgroundColor.SelectedItem = YourObject;

这就是你如何获得ListPicker的选择项,可能你需要转换为你绑定到列表Picker的对象

    private void BackgroundColor_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
      var item = (sender as ListPicker).SelectedItem;
    }