0
votes

I am using Listpicker to allow users to select color. So i used a Toolkit Listpicker with a DataTemplate that includes Textbox to display its list items. What I want is when the page loads, the previously selected color(item) gets automatically selected. But it is giving me an obvious 'System.InvalidOperationException' exception because the items are not added simply but via datatemplate textbox. Please help me :


 <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                    


            }

Actually, on simplyfing my code : BackgroundColor.SelectedIndex = 0; Doesnt work nor does BackgroundColor.SelectedItem="Red";

Help me

1
Your question is not clear! what are you trying to do?Sajeetharan
How to set the SelectedItem of a ListPicker which has DataTemplate?Atìf Shabëër
And your ItemsSource is what?Chubosaurus Software

1 Answers

0
votes

To Set the Item,

This.BackgroundColor.SelectedItem = YourObject;

This is how you get selecteditem of ListPicker, probably you need to cast to the object you bind to the list Picker

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