silverlight中不存在Flash中的场景,有的只是一个个Xaml文件,你要是愿意,也可以把它看做"场景"或"窗口",刚开始接触sl时,对于多个xaml之间如何切换,调用,传递参数感到很棘手,下面是我总结的几种方法:
1、A.xaml跳转到B.xaml
(a)首先需要定义一个公用的接口(interface),如下:
复制代码(b)A.Xaml与B.Xaml都实现该接口,代码如下:
复制代码(c)需要跳转的地方,类似下面这样处理:
复制代码上面的的意思是按钮btnChange点击后,当前"场景"将切换到Window2.xaml对应的"场景"
2、"主Xaml"中加载"子Xaml"(类似软件中的MDI窗口)
这个比较容易,在主Xaml中放置一个容器类的控件(比如ScrollViewer之类),然后指定Content就行了,参考以下代码:
1、A.xaml跳转到B.xaml
(a)首先需要定义一个公用的接口(interface),如下:
- using System.Windows;
- namespace ChildWin.Code
- {
- public interface IContent
- {
- UIElement Content { get; set; }
- }
- }
- public partial class A: UserControl, IContent
- {
- ...
- /// <summary>
- /// 实现IContent接口
- /// </summary>
- public new UIElement Content
- {
- get
- {
- return base.Content;
- }
- set
- {
- base.Content = value;
- }
- }
- }
- public partial class B: UserControl, IContent
- {
- ...
- /// <summary>
- /// 实现IContent接口
- /// </summary>
- public new UIElement Content
- {
- get
- {
- return base.Content;
- }
- set
- {
- base.Content = value;
- }
- }
- }
- private void btnChange_Click(object sender, System.Windows.RoutedEventArgs e)
- {
- (App.Current.RootVisual as IContent).Content = new Window2();
- }
2、"主Xaml"中加载"子Xaml"(类似软件中的MDI窗口)
这个比较容易,在主Xaml中放置一个容器类的控件(比如ScrollViewer之类),然后指定Content就行了,参考以下代码:
- <ScrollViewer x:Name="viewer1" Canvas.Top="40" Width="400" Height="258"></ScrollViewer>
- ...
- private void btnLoad_Click(object sender, System.Windows.RoutedEventArgs e)
- {
- if (this.viewer1.Content == null)
- {
- this.viewer1.Content = new SubWin();
- }
- }
3、"主Xaml"中以模态窗口方式弹出"子Xaml"
这个要用到sl3.0中的ChildWindow控件
(a)项目中先添加System.Windows.Controls的引用
(b)xaml文件头部加二行代码:- xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
- xmlns:vsm="clr-namespace:System.Windows;assembly=System.Windows"
- private void btnShow_Click(object sender, System.Windows.RoutedEventArgs e)
- {
- ChildWindow win = new ChildWindow();
- win.Title = "测试弹出窗口";
- win.Content = new SubWin();
- win.HasCloseButton = true;
- win.OverlayBrush = new SolidColorBrush(Colors.Gray);
- win.OverlayOpacity = 0.3;
- win.Width = 205;
- win.Height = 205;
- win.Show();
- }
可以利用构造函数来解决,参考以下代码- namespace ChildWin
- {
- public partial class SubWin : UserControl
- {
- public SubWin()
- {
- InitializeComponent();
- }
- public SubWin(DateTime dt):this()
- {
- this.calendar1.DisplayDate = dt;
- }
- }
- }
- public SubWin(DateTime dt)
- {
- InitializeComponent();
- this.calendar1.DisplayDate = dt;
- }
最后给一个综合的演示效果:
- xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"