我的 Windows Phone 7 应用程序中有一个 ListPicker,其中ItemsSource和SelectedIndex属性都绑定到我的 ViewModel。SelectedIndex 使用双向绑定。项目和 SelectedIndex 在应用程序启动时正确填充。但是,当我在 ViewModel 中修改 SelectedIndex 属性时,ListPicker 的 TextBox 变为空白,就好像没有选定的项目一样。如果我进入完整模式并检查列表中的选定项目,则选择了正确的项目。
这是 ListPicker xaml 代码:
<toolkit:ListPicker Name="TheListPicker" ItemsSource="{Binding TheItems}" CacheMode="BitmapCache" FullModeHeader="{Binding Path=Resources.TheHeader, Source={StaticResource LocalizedStrings }}" SelectedIndex="{Binding TheCurrentIndex, Mode=TwoWay}" IsEnabled="{Binding IsViewEnabled}" TabIndex="0" >
<toolkit:ListPicker.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<TextBlock Text="{Binding Name}" FontFamily="{StaticResource PhoneFontFamilySemiBold}" FontSize="{StaticResource PhoneFontSizeMediumLarge}" />
</StackPanel>
</DataTemplate>
</toolkit:ListPicker.ItemTemplate>
<toolkit:ListPicker.FullModeItemTemplate>
<DataTemplate>
<StackPanel x:Name="item" Orientation="Horizontal" Margin="5, 24, 0, 24">
<TextBlock Margin="15, 0, 0, 0" Text="{Binding Name}" FontSize="40" TextWrapping="Wrap" />
</StackPanel>
</DataTemplate>
</toolkit:ListPicker.FullModeItemTemplate>
</toolkit:ListPicker>
这是我的 ViewModel 的简化版本:
[DataMember]
public ObservableCollection<ItemEntity> TheItems
{
get
{
if (this.theItems == null)
{
this.theItems = new ObservableCollection<ItemEntity>();
}
return this.theItems;
}
set
{
this.theItems = value;
}
}
[DataMember]
public int TheCurrentIndex
{
get
{
return this.theCurrentIndex;
}
set
{
if (value != this.theCurrentIndex)
{
this.theCurrentIndex = value;
NotifyPropertyChanged("TheCurrentIndex");
NotifyPropertyChanged("IsSomeOtherPropertyEnabled");
}
}
}
以下是 MainPage.xaml.cs 中的相关代码(App_ViewModelChanged 是在应用程序启动时执行的一些异步操作完成时调用的事件处理程序):
private void App_ViewModelChanged(object sender, ViewModelChangedEventArgs e)
{
BindToViewModel();
}
private void BindToViewModel()
{
this.DataContext = this.ViewModel;
this.ViewModel.IsViewEnabled = true;
}
private void SomeAsyncMethodCompleted(object sender, DetectCompletedEventArgs e)
{
if (e.Error == null)
{
this.ViewModel.TheCurrentIndex = e.Result;
}
}
这个问题并非一直都在发生。大约有 50% 的时间发生。它似乎在应用程序生命周期中只发生一次,然后再也不会发生。此外,当我从 2011 年 2 月版的 Silverlight 控制工具包切换到 2011 年 8 月版时,问题开始出现。以前从来没有遇到过这个问题。
这是一个已知的问题?