2018/10/17

[C#] WPF Object Array

在寫WPF的介面時,如果需要用到大量相同的物件,比較直接的方法就是在xaml裡面一直複製貼上程式碼。

像是如果要顯示出一排一樣的圖片像這樣:

在xmal裡面最直接的寫法就是像這樣寫一堆一樣的程式碼:
<Grid>
    <Canvas x:Name="CanvasWindow" Height="400" VerticalAlignment="Top" HorizontalAlignment="Left" Width="500" >
        <Image x:Name="img01" Canvas.Left="0" Height="100" Width="100" Source="Image/mouse.png" Stretch="Fill" Visibility="Visible" Canvas.Top="0"/>
        <Image x:Name="img02" Canvas.Left="100" Height="100" Width="100" Source="Image/mouse.png" Stretch="Fill" Visibility="Visible" Canvas.Top="0"/>
        <Image x:Name="img03" Canvas.Left="200" Height="100" Width="100" Source="Image/mouse.png" Stretch="Fill" Visibility="Visible" Canvas.Top="0"/>
        <Image x:Name="img04" Canvas.Left="0" Height="100" Width="100" Source="Image/mouse.png" Stretch="Fill" Visibility="Visible" Canvas.Top="100"/>
        <Image x:Name="img05" Canvas.Left="100" Height="100" Width="100" Source="Image/mouse.png" Stretch="Fill" Visibility="Visible" Canvas.Top="100"/>
        <Image x:Name="img06" Canvas.Left="200" Height="100" Width="100" Source="Image/mouse.png" Stretch="Fill" Visibility="Visible" Canvas.Top="100"/>
    </Canvas>
</Grid>


但是如果不想把程式碼都寫在xmal裡面的話,也可以在cs檔裡面用array程式碼搞定:
private Image[] images;
public MainWindow()
{
    InitializeComponent();
    images = new Image[6];
    for (int i = 0; i < images.Length; i++)
    {
        images[i] = new Image();
        images[i].Source = new BitmapImage(new Uri(@"Image/mouse.png", UriKind.Relative));
        images[i].Width = 100;
        images[i].Height = 100;
        images[i].Stretch = Stretch.Fill;
        images[i].Visibility = Visibility.Visible;
        CanvasWindow.Children.Add(images[i]);
        Canvas.SetLeft(images[i], (100 * i));
        Canvas.SetTop(images[i], 0);
    }
}

如果要畫二維陣列的圖像這樣:

cs程式碼可以這樣寫:
static int array_x = 3, array_y = 2;
private Image[,] images;
public MainWindow()
{
    InitializeComponent();
    images = new Image[array_y,array_x];
    for (int j = 0; j < array_y; j++)
    {
        for (int i = 0; i < array_x; i++)
        {
            images[j,i] = new Image();
            images[j,i].Source = new BitmapImage(new Uri(@"Image/mouse.png", UriKind.Relative));
            images[j,i].Width = 100;
            images[j,i].Height = 100;
            images[j,i].Stretch = Stretch.Fill;
            images[j,i].Visibility = Visibility.Visible;
            CanvasWindow.Children.Add(images[j,i]);
            Canvas.SetLeft(images[j, i], (100 * i));
            Canvas.SetTop(images[j, i], (100 * j));
        }
    }
}

像這樣如果有大量一樣的物件要畫,可以根據App的UI架構參考看看要用哪一種寫法比較好控制整體。
End

沒有留言:

張貼留言