[Silverlight]動態讀取圖片以及影片 ----- Day4
今天,我們回歸到Programmer的身份,來學習如何處理在Silverlight動態讀取圖片以及影片。
首先,新增一個Silverlight的專案,如果你不知道要怎麼新增,請參考[Silverlight]Hello Siverlight ----- Day 1
1.
然後在Page.xaml中輸入下列程式碼,這邊設定一個Border中放置一個Image File,然後有一個讀取的Button
,然後Button的Click事件為ReadStream:
<UserControl x:Class="SLApp_D4.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Border BorderBrush="Black" BorderThickness="3" Margin="5">
<Image Grid.Row="0" Margin="15" x:Name="Image1"
HorizontalAlignment="Stretch" Height="150" />
</Border>
<Button Grid.Row="1" Content="讀取" FontSize="12" Height="25" Width="30" Click="ReadStream" />
</Grid>
</UserControl>
2.
接下來我們在CodeBehide中的ReadStream事件寫入下列程式碼:
//讀取圖片
void ReadStream(object sender, EventArgs args)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Jpeg Files(*.jpg)|*.jpg|All Files(*.*)|*.*";
if (dialog.ShowDialog() == true)
{
using (Stream stream = dialog.File.OpenRead()) //讀取Stream
{
//設定image
BitmapImage bmpImage = new BitmapImage();
bmpImage.SetSource(stream);
Image1.Source = bmpImage;
}
}
}
3.
然後按下F5執行,您可以透過讀取按鈕去顯示您所選擇的jpg圖片:
接下來,我們來顯示影片:
1.
變更Xaml Code如下,新增一個Border,設定其屬性Grid.Row="1",然後內嵌一個MediaElement物件,
然後設定名稱為video1:
<UserControl x:Class="SLApp_D4.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="600">
<Grid x:Name="LayoutRoot" Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Border BorderBrush="Black" Grid.Row="0" BorderThickness="3" Margin="5">
<Image Grid.Row="0" Margin="15" x:Name="Image1"
HorizontalAlignment="Stretch" Height="150" />
</Border>
<Border BorderBrush="Black" Grid.Row="1" BorderThickness="3" Margin="5">
<MediaElement Margin="15" x:Name="video1" HorizontalAlignment="Stretch"></MediaElement>
</Border>
<Button Grid.Row="2" Content="讀取" FontSize="12" Height="25" Width="30" Click="ReadStream" />
</Grid>
</UserControl>
2.
變更程式碼如下:
//讀取影片
void ReadStream(object sender, EventArgs args)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "WMV Files (*.wmv)|*.wmv|All Files(*.*)|*.*";
if (dialog.ShowDialog() == true)
{
using (Stream stream = dialog.File.OpenRead()) //讀取Stream
{
video1.SetSource(stream);
video1.Play();
}
}
}
3.
執行結果:
試煉大會,我們下次見。
如果您有微軟技術開發的問題,可以到MSDN Forum發問。
如果您有微軟IT管理的問題,可以到TechNet Forum發問喔。