具有DataTemplate的ListPicker的SelectedIndex或SelectedItem
本文关键字:SelectedItem SelectedIndex ListPicker DataTemplate 具有 | 更新日期: 2023-09-27 18:20:55
我使用Listpicker来允许用户选择颜色。因此,我使用了一个带有DataTemplate的Toolkit Listpicker,其中包括显示其列表项的Textbox。我想要的是当页面加载时,之前选择的颜色(项目)会自动被选中。但它给了我一个明显的"System.InvalidOperationException"异常,因为这些项不是简单地添加的,而是通过数据模板文本框添加的。请帮帮我:
<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;Doesnt work也没有BackgroundColor.SelectedItem="红色";
帮助我
要设置项目,
This.BackgroundColor.SelectedItem = YourObject;
这就是获取ListPicker的selecteditem的方法,可能需要将其转换为绑定到列表Picker 的对象
private void BackgroundColor_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var item = (sender as ListPicker).SelectedItem;
}