最近初学Silverlight,有海量的问题需要解决。本来想把所有看到的英文版的好东西都在这里翻译出来,方便英文不佳(虽然我的英文也不好)的初学兄弟,同时翻译的过程也是学习的过程。无奈时间实在紧张。这次就先把这个切换页面的方法记录一下。
这个做法是来自“Jesse Liberty”的视频“USING MULTIPLE PAGES, PART 1”,基本方法是创建一个PageSwticher,这个PageSwitcher不直接显示页面,而是作为一个后台,负责切换各个页面。
具体做法是:
新建一个UserControl,名字可以叫做PageSwitcher。然后将PageSwitcher.xaml中的Grid控件去掉,编程下面这样:
<
UserControl
x:Class
="SilverlightDemo.PageSwitcher"
xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation%22
xmlns:x=" http://schemas.microsoft.com/winfx/2006/xaml%22 >
</ UserControl >
xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation%22
xmlns:x=" http://schemas.microsoft.com/winfx/2006/xaml%22 >
</ UserControl >
然后在后台代码中增加一个方法,比如叫做SwitchPage,用来切换页面,然后在构造函数中调用,用来显示第一个要显示页面:
public
partial
class
PageSwitcher : UserControl
{
public PageSwitcher()
{
InitializeComponent();
SwitchPage( new Page()); // 显示第一个要显示的页面
}
/// <summary>
/// 切换页面
/// </summary>
/// <param name="newPage"> 需要被切换到的页面 </param>
public void SwitchPage(UserControl newPage)
{
this .Content = newPage;
}
}
{
public PageSwitcher()
{
InitializeComponent();
SwitchPage( new Page()); // 显示第一个要显示的页面
}
/// <summary>
/// 切换页面
/// </summary>
/// <param name="newPage"> 需要被切换到的页面 </param>
public void SwitchPage(UserControl newPage)
{
this .Content = newPage;
}
}
然后在我们的各个页面中,在需要切换页面的事件响应方法中,只需要这么做:
private
void
btn_Click(
object
sender, RoutedEventArgs e)
{
PageSwitcher switcher = this .Parent as PageSwitcher;
switcher.SwitchPage( new AnotherPage());
}
{
PageSwitcher switcher = this .Parent as PageSwitcher;
switcher.SwitchPage( new AnotherPage());
}
最后,我们需要修改app.xaml.cs中的Application_Startup方法,修改起始页面
private
void
Application_Startup(
object
sender, StartupEventArgs e)
{
this .RootVisual = new PageSwitcher();
}
{
this .RootVisual = new PageSwitcher();
}