在 WPF 撥放影像檔需使用 MediaElement 控制項
本篇將介紹兩種撥放方式,第一種為載入即開始撥放影音,另一種是需透過點選按鈕才開始撥放。
版面配置
xaml
在Grid加入Grid.Triggers 並將設計的code寫在裡面
<Grid>
<Grid.Triggers>
</Grid.Triggers>
</Grid>
載入即撥放設計: (MediaElement 控制項名稱為 mediaElement1)
<EventTrigger SourceName="mediaElement1" RoutedEvent="MediaElement.Loaded">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<MediaTimeline
Source="Wildlife.wmv"
Storyboard.TargetName="mediaElement1"
RepeatBehavior="Forever"
/>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
點按鈕撥放:(mediaElement2)
<EventTrigger SourceName="button1" RoutedEvent="Button.Click">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<MediaTimeline
Source="Wildlife.wmv"
Storyboard.TargetName="mediaElement2"
RepeatBehavior="Forever"
/>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
完整xaml
<Window x:Class="PlayVideoFormWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="PlayVideo" Height="481" Width="624">
<Grid>
<Grid.Triggers>
<EventTrigger SourceName="mediaElement1" RoutedEvent="MediaElement.Loaded">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<MediaTimeline
Source="Wildlife.wmv"
Storyboard.TargetName="mediaElement1"
RepeatBehavior="Forever"
/>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
<EventTrigger SourceName="button1" RoutedEvent="Button.Click">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<MediaTimeline
Source="Wildlife.wmv"
Storyboard.TargetName="mediaElement2"
RepeatBehavior="Forever"
/>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Grid.Triggers>
<MediaElement Height="204" HorizontalAlignment="Left" Margin="39,101,0,0" Name="mediaElement1" VerticalAlignment="Top" Width="224" />
<Button Content="點一下開始撥放" Height="50" HorizontalAlignment="Left" Margin="391,311,0,0" Name="button1" VerticalAlignment="Top" Width="111" />
<MediaElement Height="204" HorizontalAlignment="Left" Margin="325,101,0,0" Name="mediaElement2" VerticalAlignment="Top" Width="235" />
<Label Content="載入即開始撥放" Height="39" HorizontalAlignment="Left" Margin="74,48,0,0" Name="label1" VerticalAlignment="Top" Width="189" FontSize="18" />
<Label Content="點按鈕才開始撥放" Height="37" HorizontalAlignment="Left" Margin="369,48,0,0" Name="label2" VerticalAlignment="Top" FontSize="18" />
<MediaElement Height="120" HorizontalAlignment="Left" Margin="738,434,0,0" Name="mediaElement3" VerticalAlignment="Top" Width="160" />
</Grid>
</Window>
參考網站:
http://msdn.microsoft.com/zh-tw/cc964157.aspx#
http://msdn.microsoft.com/zh-tw/library/ms752338.aspx
範例下載:PlayVideoFormWPF.rar
留言列表