04、数据绑定控件 ListBox 的一个 Bug

 

同事这两天在做 universal 项目的时候,遇到一个诡异的问题,即使设置 Page 为

缓存状态, 在页面跳转后, ListBox 的位置不会被缓存,怀疑是页面的缓存状态出了问题:

this.NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Enabled;

 

写了一个 demo,测试了一下:

1)在程序启动的时候,默认显示 PivotPage 页面。分别放置 ListView、 ItemsControl、ListBox 控件:

<Pivot Title="Pivot">
    <PivotItem Header="PivotItem 1">
        <Grid>
            <ListView x:Name="lv1" ItemsSource="{Binding list}"/>
        </Grid>
    </PivotItem>

    <PivotItem Header="PivotItem 2">
        <Grid>
            <ScrollViewer>
                <ItemsControl x:Name="lv2" ItemsSource="{Binding list}"/>
            </ScrollViewer>
        </Grid>
    </PivotItem>

    <PivotItem Header="PivotItem 3">
        <Grid>
            <ListBox IsTapEnabled="False" x:Name="lv3" ItemsSource="{Binding list}"/>
        </Grid>
    </PivotItem>
</Pivot>
<Button Content="Page2" Click="Button_Click" HorizontalAlignment="Left" Margin="261,531,0,0" VerticalAlignment="Top"/>

 

2)在 C# 页面,进行数据绑定:

 public List<string> list { get; set; }

 public PivotPage()
 {
     this.InitializeComponent();

     this.NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Enabled;

     // 填充字符串
     list = new List<string>();

     for (int i = 1; i < 200; i++)
     {
         list.Add("测试内容 : " + i);
     }

     // 设置当前页面的上下文为 this
     this.DataContext = this;
 }


 

放置一个跳转按钮:

 private void Button_Click(object sender, RoutedEventArgs e)
 {
     Frame.Navigate(typeof(Page2));
 }


页面启动后,分别滑动  ListView、ItemsControl、ListBox 控件:

 

 

3)点击 按钮,跳转到 Page2, 然后再 点击 GoBack 按钮:

 

回到 PivotPage 后, 滑动 ListBox 控件,就会诡异的返回到第一项。而 ListView 和 ItemsControl 没有这个问题:

 

    另外,我怀疑,在 store app 中,ListBox 其实是作为一个  multiple ListPicker 用的,

数据绑定重点使用 ListView 和 GridView 了,个人的猜测 ....

 

补充:

 1、针对 ListBox:

     ItemsPanel 属性 默认应该是 VirtualizingStackPanel ,当返回的时候,会返回顶部:

 

 

当换为 ItemsStackPanel 时,就没问题了,导航返回后,单击不会返回顶部:

(ItemsStackPannel: MSDN)

 

 

 

2、 ListView 控件在做 折行布局时,如果 ListView 的ItemsPanel属性为WrapGrid 则在 Navigate  back 的时候,

如果滑动列表,则会返回顶部;如果为 ItemsWrapGrid,则不会:

<ListView x:Name="lv1" ItemsSource="{Binding list}" ItemTemplate="{StaticResource template}">
    <ListView.ItemsPanel>
        <ItemsPanelTemplate>                                
            <ItemsWrapGrid  Orientation="Horizontal"/> <!-- 如果使用 <WrapGrid/> 作为容器,则出现导航回来后,返回顶部-->
        </ItemsPanelTemplate>
    </ListView.ItemsPanel>
</ListView>


 

 

 

Demo 下载链接

 

Demo2 下载链接

 

posted @ 2015-03-06 17:03  博琼  阅读(530)  评论(1编辑  收藏  举报