选择editem或选择用于列表选择器的索引

本文关键字:选择 索引 选择器 用于 editem 列表 | 更新日期: 2023-09-27 18:21:32

当应用程序打开时,ListPicker的selectedItem,即"BackgroundColor"必须来自变量。如何做到这一点?

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中的项实际上来自类/列表。现在如何在页面打开时将BackgroundColor列表选择器设置为黑色(预选颜色)?

选择editem或选择用于列表选择器的索引

您需要将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;
}