2011-08-16 48 views
0

我在XAML中有两个listBox ItemTemplate。但我无法通过Page的orientationChanged事件更改它以更改DataTemplate。 这里是代码:基于页面方向更改DataTemplate

protected override void OnOrientationChanged(OrientationChangedEventArgs e) 
    { 
     if (e.Orientation == PageOrientation.Landscape || 
      e.Orientation == PageOrientation.LandscapeLeft || 
      e.Orientation == PageOrientation.LandscapeRight) 
     { 
      this.HeadLineListBox.ItemTemplate = (DataTemplate)this.Resources["L_headerTemplate"]; 
     } 

     else if (e.Orientation == PageOrientation.Portrait || 
       e.Orientation == PageOrientation.PortraitDown || 
       e.Orientation == PageOrientation.PortraitUp) 
     { 
      this.HeadLineListBox.ItemTemplate = (DataTemplate)this.Resources["P_headerTemplate"]; 
     } 

     base.OnOrientationChanged(e); 
    } 

当我第一次到如果方向是纵向的页面,它会显示人像DataTemplate中所有的时间,即使我改变了方向。所以,当我第一次进入页面时,它是Landscape.Someone可以帮助我吗?

PS:我用这个帖子的方式:http://wp7-developer.com/code-snippet/changing-the-datatemplate-based-on-page-orientation/但是它仍然不行。

+0

我尝试这里提到遵循的方法,我没有工作过。 http://wp7-developer.com/code-snippet/changing-the-datatemplate-based-on-page-orientation/ – Joel

+0

我已经使用上述技术根据页面的方向更改布局。 OrientationChanged事件是否未触发或数据模板是否未更新? –

+0

我在OrientationChanged事件中做了一个断点。当方向改变时它真的被触发了,但是页面没有像预期的那样工作。 – Joel

回答

1

您需要将分配的ItemSource新的ItemTemplate之后再次与应用更新的ItemTemplate为 -

if (e.Orientation.ToString().Contains("Portrait")) 

    lstData.ItemTemplate = 

    (DataTemplate)this.Resources["listPortrait"]; 

else 

    lstData.ItemTemplate = 

    (DataTemplate)this.Resources["listLandscape"]; 

lstData.ItemsSource = null; 

lstData.ItemsSource = ((Products)this.Resources["productCollection"]).DataCollection; 
+0

这是一种方法,但如果你有更好的方法,请回复。 – Joel

0

不幸的是,我不认为这是行得通的。将项目添加到列表框时应用ItemTemplate。你可以用下面的代码片段和你自己单独的模板来测试:

// Constructor 
public MainPage() 
{ 
    InitializeComponent(); 
    Loaded += (sender, e) => 
    { 
     DispatcherTimer t = new DispatcherTimer(); 
     t.Interval = TimeSpan.FromSeconds(5); 
     t.Tick += (sender2, e2) => 
     { 
      MyListBox.Items.Add(this.Orientation.ToString()); 
     }; 
     t.Start(); 
    }; 
} 

效果很有趣。在我的样本,下面的输出写入到列表框,我旋转模拟器:

THIS IS THE PORTRAIT TEMPLATE: PortraitUp 
THIS IS THE LANDSCAPE TEMPLATE: LandscapeLeft 
THIS IS THE LANDSCAPE TEMPLATE: LandscapeRight 
THIS IS THE LANDSCAPE TEMPLATE: LandscapeLeft 
THIS IS THE PORTRAIT TEMPLATE: PortraitUp 

已经为我工作在过去是使用两个完全不同的布局管理器的另一种方法 - 一个人像优化布局,另一个针对风景进行了优化 - 并根据方向的变化切换每种风景的可见性/不透明度。我过去使用过这种技术,它提供了很好的可混合性和良好的性能(如果你的页面不太复杂)。我仍然在努力争取“最好”的方法,但至少我知道这个方法有效。

/克里斯

+0

感谢分享。这是一种可以工作的方法。但是我的页面有点复杂,它表现不佳。 – Joel

+0

我觉得你被卡住了,要么写一个模板,将横向和纵向工作,或重新加载方向更改时的列表框。前者是最佳解决方案,我几乎不会推荐第二种解决方案。祝你好运 - 确保你回到这里,让我们知道你是如何解决这个问题的。 –

+0

我发现了代码后的另一种方法:this.HeadLineListBox.ItemTemplate =(DataTemplate)this.Resources [“P_headerTemplate”];我重新加载绑定到列表的数据。这真的奏效了。好吧,如你所知,这不是最好的方法。有人可能有更好的方法。如果你知道,请告诉我。 – Joel