Silverlight实用窍门系列:36.Silverlight中播放视频和打印文档【附带源码实例】
在silverlight实际项目中时常会需要播放视频和打印文档,在本节中我们将制作一个最简单的播放视频和打印文档的实例。
一、播放WMV视频
首先我们创建一个Silverlight应用程序SLShowVideo,然后放一个示例Wmv视频在SLShowVideo.web项目的根目录下面。
然后我们在Xaml文档中放入一个MediaElement控件,并写入以下代码:
<MediaElement Height="377" HorizontalAlignment="Left" Margin="8,31,0,0"
Name="showVideo" VerticalAlignment="Top" Width="583" />
<Button Content="播 放" Height="28" HorizontalAlignment="Left" Margin="194,428,0,0"
Name="button1" VerticalAlignment="Top" Width="99" Click="button1_Click_1" />
<Button Content="暂 停" Height="28" HorizontalAlignment="Left" Margin="333,428,0,0"
Name="button3" VerticalAlignment="Top" Width="99" Click="button3_Click" />
<Button Content="停 止" Height="28" HorizontalAlignment="Left" Margin="468,428,0,0"
Name="button2" VerticalAlignment="Top" Width="99" Click="button2_Click" />
<Button Content="加载视频" Height="28" HorizontalAlignment="Left" Margin="57,428,0,0"
Name="button4" VerticalAlignment="Top" Width="99" Click="button1_Click"/>
最后我们写入以下代码加载视频并且控制视频的播放:
#region 播放视频
private void button1_Click(object sender, RoutedEventArgs e)
{
//加载视频
this.showVideo.Source = new Uri(GetURL()+"/sampleVideo.wmv");
}
/// <summary>
/// 获取当前网站的Url前缀
/// </summary>
/// <returns></returns>
public static string GetURL()
{
ScriptObject location = (HtmlPage.Window.GetProperty("location") as ScriptObject);
object r = location.GetProperty("href");
string URL = r.ToString().Substring(0, r.ToString().LastIndexOf('/'));
//截取到当前SILVERLIGHT程序存放网络URL的前缀
return URL;
}
private void button3_Click(object sender, RoutedEventArgs e)
{
//暂停
this.showVideo.Pause();
}
private void button2_Click(object sender, RoutedEventArgs e)
{
//停止
this.showVideo.Stop();
}
private void button1_Click_1(object sender, RoutedEventArgs e)
{
//播放
this.showVideo.Play();
}
#endregion
二、打印文档
首先我们看XAML文档。添加一个Canvas元素,元素内的所有内容就是我们即将要打印(当然你也可以设置打印Grid等元素的内容)。
<Canvas Height="376" HorizontalAlignment="Left" Margin="611,32,0,0" Name="canvas1"
VerticalAlignment="Top" Width="369" >
<sdk:Label Width="85" Canvas.Left="9" Content="第一个打印程序" Canvas.Top="27" />
<sdk:Label Canvas.Left="11" Canvas.Top="60" Height="16" Content="第二个打印程序"
Name="label1" Width="86" />
</Canvas>
<Button Content="打印" Height="34" HorizontalAlignment="Left" Margin="747,426,0,0"
Name="btnPrint" VerticalAlignment="Top" Width="110" Click="btnPrint_Click" />
#region 打印文档
PrintDocument print;
private void btnPrint_Click(object sender, RoutedEventArgs e)
{
print = new PrintDocument();
//添加一个打印页面事件以设置需要打印的控件
print.PrintPage += new EventHandler<PrintPageEventArgs>(print_PrintPage);
print.Print("canvas1");
}
void print_PrintPage(object sender, PrintPageEventArgs e)
{
//设置打印this.canvas1的所有内容
e.PageVisual = this.canvas1;
}
#endregion