XAMLを使わないWPF入門06「画像を表示」

コンピュータ

画像ファイルを読み込んで表示するサンプルコードです。

プロジェクトの作成

cd (mkdir NoXAML06)
dotnet new wpf -f net8.0
rm *.xaml

ソースコード

ファイル名:NoXAML06.csproj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net8.0-windows</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <UseWPF>true</UseWPF>
    <StartupObject>NoXAML06.App</StartupObject>
  </PropertyGroup>

</Project>

ファイル名:App.xaml.cs

using System.Windows;

namespace NoXAML06;

/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
    private static void App_Startup(object sender, StartupEventArgs e)
    {
        // ウィンドウ本体をコードで生成
        var window = new MainWindow
        {
            Title = "画像を表示",
            Width = 400,
            Height = 300,
        };
        window.Show();
    }
    // エントリポイント
    [STAThread]
    public static void Main()
    {
        var app = new App();
        // Startup イベントでウィンドウを生成
        app.Startup += App_Startup;
        app.Run();
    }
}

ファイル名:MainWindow.xaml.cs

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace NoXAML06;

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    // ウィンドウ内に配置する UI を組み立てる
    private static UIElement BuildContent()
    {
        BitmapImage bi = new BitmapImage();
        bi.BeginInit();
        bi.UriSource = new Uri(@"画像ファイルのパス", UriKind.Absolute);
        bi.EndInit();

        var image = new Image
        {
            Stretch = Stretch.Uniform,
            Source = bi,
        };

        // GridにImageを載せて返す
        return new Grid
        {
            Children = { image }
        };        
    }

    public MainWindow()
    {
        Content = BuildContent();  // 中身の UI 要素を返すメソッド
    }
}

実行

dotnet run

コメント