我正在尝试在 Windows Phone 7 UserControl 中对 ListPicker 的 SelectedIndex 属性进行双向绑定。
当我设置 DataContext 时,它会引发以下异常:
SelectedIndex must always be set to a valid value.
这是 XAML 代码
<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<toolkit:ListPicker
Grid.Row="0"
x:Name="List1"
SelectionChanged="Picker_SelectionChanged"
SelectedIndex="{Binding PickerSelectedIndex, Mode=TwoWay}"
ItemTemplate="{StaticResource PickerTemplate}"
ItemsSource="{Binding MyList}"/>
</Grid>
以及 DataContext 中的代码
private ObservableCollection<MyClass> myList = null;
public ObservableCollection<MyClass> MyList
{
get { return this.myList; }
set
{
if (value != this.myList)
{
this.myList= value;
NotifyPropertyChanged("MyList");
this.PickerSelectedIndex = 0;
}
}
}
private int pickerSelectedIndex = 0;
public int PickerSelectedIndex
{
get
{
return this.pickerSelectedIndex;
}
set
{
this.pickerSelectedIndex= value;
}
}
放一个断点PickerSelectedIndex.get
我可以看到它被正确返回(0
)。我确定问题是SelectedIndex="{Binding PickerSelectedIndex, Mode=TwoWay}"
因为删除此行解决了问题,并且我可以看到 ListPicker 正确加载了来自 MyList 的数据。
看不出哪里有问题...