由于想要顯示不同類型的圖檔,就建立了一個TabControl,再在每一個TabItem裡面添加了一個Image控件來顯示圖檔。還加入了一些按鈕用來控制上一張或者下一張圖檔的顯示。
<Grid>
<TabControl Height="500" HorizontalAlignment="Left" Margin="460,12,0,0" Name="tabControl" VerticalAlignment="Top" Width="420">
<TabItem Header="Glass" Name="tabItem1">
<Grid>
<Image Height="460" Margin="0,0,0,0" Name="imageGlass" Stretch="Fill" VerticalAlignment="Top" Width="400" />
</Grid>
</TabItem>
<TabItem Header="Watch" Name="tabItem2" >
<Grid>
<Image Height="460" Margin="0,0,0,0" Name="imageWatch" Stretch="Fill" VerticalAlignment="Top" Width="400" />
</Grid>
</TabItem>
</TabControl>
<Image Height="500" HorizontalAlignment="Left" Margin="12,12,0,0" Name="imageBody" Stretch="Fill" VerticalAlignment="Top" Width="420" />
<Button Content="确 定" Height="23" HorizontalAlignment="Left" Margin="320,525,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
<Button Content="上一張" Height="23" HorizontalAlignment="Left" Margin="540,525,0,0" Name="bottonPrior" VerticalAlignment="Top" Width="75" Click="buttonPrior_Click" />
<Button Content="下一張" Height="23" HorizontalAlignment="Left" Margin="710,525,0,0" Name="bottonNext" VerticalAlignment="Top" Width="75" Click="buttonNext_Click" />
</Grid>
因為需要顯示檔案夾下的圖檔,就要得到檔案夾内圖檔的路徑,我将這些圖檔分類後放在了不同的檔案夾下,并定義了路徑數組:
string[] pathGlass = System.IO.Directory.GetFiles("E:\\C#\\201303\\glass");
string[] pathWatch = System.IO.Directory.GetFiles("E:\\C#\\201303\\watch");
int numGlass = 0;
int numWatch = 0;
pathGlass數組記憶體放了glass檔案夾下的所有圖檔的路徑資訊,并為該數組定義了遊标numGlass,為周遊時确定圖檔索引。
在上面XAML架構設計中,定義的Image控件,通過調用Source可以顯示圖檔,是以需要将圖檔運用路徑資訊得到該圖檔的位圖資訊傳給相應的Source。于是就定義了如下的方法:
private BitmapImage colorBitmap(string path)
{
BitmapImage bitmapImage;
bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = System.IO.File.OpenRead(path);
bitmapImage.EndInit();
return bitmapImage;
}
這樣一來隻需調用該方法就能将圖檔傳遞給界面顯示:
public MainWindow()
{
InitializeComponent();
if (pathGlass.Length>=1)
{
this.imageGlass.Source = colorBitmap(pathGlass[0]);
}
if (pathWatch.Length >= 1)
{
this.imageWatch.Source = colorBitmap(pathWatch[0]);
}
}
接下來就是點選按鈕事件了,因為定義了TabControl控件,當選中某一個TabItem後,相應的按鈕事件就要執行該TabItem下的内容了。就拿點選“上一張”按鈕而言:
private void buttonPrior_Click(object sender, RoutedEventArgs e)
{
if (this.tabItem1.IsSelected)
{
if (numGlass == 0)
{
numGlass = pathGlass.Length - 1;
}
else numGlass--;
this.imageGlass.Source = colorBitmap(pathGlass[numGlass]);
}
if (this.tabItem2.IsSelected)
{
if (numWatch == 0)
{
numWatch = pathWatch.Length - 1;
}
else numWatch--;
this.imageWatch.Source = colorBitmap(pathWatch[numWatch]);
}
}
最終效果圖為:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZwpmL4ITN58VM5MDO3YzM2MTMvwVOx8CXzAzMxAjMvw1ckF2bsBXdvwFdl5mLuR2cj5Set1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
剛開始學C#沒多久,左邊的空白部分是打算顯示Kinect攝像結果的。這也是第一份CSDN的博文,以後打算好好學習,經常光顧CSDN,想要堅持把學到的知識記錄下來。