当App打开时,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
中的项目来自Class / List。现在,只要页面打开,如何将BackgroundColor listpicker设置为Black(PreSelectedColor)?
答案 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;
}