百度了那么多,暂时没发现别人用我这种方法,大家可以尝试下。
1、定义2个Page,名字为Page1.xaml,Page2.xaml
2、在Mainwindow放一个Frame来做容器
3、在Mainwindow定义一个数组:
struct PagesAndName
{
public string PageName;
public Page PageForNavigate;
}
PagesAndName[] ThePagesStr;
4、初始化他们,并显示第一个Page1:
ThePagesStr = new PagesAndName[3];
ThePagesStr[0].PageName = "Page1.xaml";
ThePagesStr[0].PageForNavigate = new Page1();
ThePagesStr[1].PageName = "Page2.xaml";
ThePagesStr[1].PageForNavigate = new Page2();
ThePagesStr[2].PageName = "Page3.xaml";
ThePagesStr[2].PageForNavigate = new Page3();
TheFrame.Navigate(ThePagesStr[0].PageForNavigate);
5、现在响应button事件,这些button事件一样,只是tag设置为page名字,在事件中匹配tag和上面的数组,找到page后然后nav过去,看代码:
<StackPanel>
<Button Opacity="0.5" Tag="Page1" Click="BtnShow_Click">1</Button>
<Button Tag="Page2" Click="BtnShow_Click">2</Button>
<Button Tag="Page3" Click="BtnShow_Click">3</Button>
</StackPanel>
private void BtnShow_Click(object sender, RoutedEventArgs e)
{
// 切换为Page1
Button Btn = sender as Button;
string PageName = Btn.Tag.ToString()+".xaml";
Page ThePage=null;
// 从数组中找到然后nav过去
int i;
for(i = 0; i < ThePagesStr.Length; i++)
{
if(PageName == ThePagesStr[i].PageName)
{
ThePage = ThePagesStr[i].PageForNavigate;
break;
}
}
if (i == ThePagesStr.Length || ThePage==null)
return;
//TheFrame.Navigate(new Uri(PageName, UriKind.Relative));
TheFrame.Navigate(ThePage);
}
怎么样,爽歪歪吧?