listite的selecteditem或selectedindex

时间:2014-09-11 08:08:43

标签: c# windows-phone-8 indexing selecteditem listpicker

当App打开时,ListPicker的selectedItem即“B​​ackgroundColor”必须来自变量。怎么做到这一点?

XAML:

<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"  Margin="0 14 0 0" HorizontalAlignment="Center">
                <TextBlock Name="BackgroundColor" 
                            Text="{Binding BackGroundColorString}"
                            FontSize="35" 
                            Margin="10,10"                              
                            TextAlignment="Center"
                           FontFamily="/Assets/Fonts/AGENCYR.TTF#Agency FB"
               />
            </StackPanel>
        </Grid>
    </DataTemplate>
</phone:PhoneApplicationPage.Resources>        

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

C#:

public class BackGroundlistPickerClass
{
    public string BackGroundColorString
    {
        get;
        set;
    }
}

List<BackGroundlistPickerClass> BackGroundColorList = new List<BackGroundlistPickerClass>();

public void ImplementListPickeritems() //Listpickers
{
    BackGroundColorList.Add(new BackGroundlistPickerClass() { BackGroundColorString = "White (Default)" });
    BackGroundColorList.Add(new BackGroundlistPickerClass() { BackGroundColorString = "Black" });
    BackGroundColorList.Add(new BackGroundlistPickerClass() { BackGroundColorString = "Light Grey" });

}

string PreSelectedColor="Black";
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
    BackgroundColor.SelectedItem=PreSelectedColor; //  ERROR COMES ON THIS LINE
}

BackgroundColor.SelectedItem无法正常工作,因为BackgroundColor中的项目来自Class / List。现在,只要页面打开,如何将BackgroundColor listpicker设置为Black(PreSelectedColor)?

1 个答案:

答案 0 :(得分:2)

您需要将SelectedItem设置为ItemsSource中的项目。您可以尝试这种方式,假设BackGroundColorList属性用于ItemsSource

string PreSelectedColor="Black";
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
    var defaultColor = 
            BackGroundColorList.FirstOrDefault(o => o.BackGroundColorString == PreSelectedColor);
    BackgroundColor.SelectedItem = defaultColor;
}