3

ビットマップ画像変数があり、それをxamlウィンドウにバインドしたいと思います。

System.Reflection.Assembly thisExe;
        thisExe = System.Reflection.Assembly.GetExecutingAssembly();
        string[] resources = thisExe.GetManifestResourceNames();
        var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("SplashDemo.Resources.Untitled-100000.png");
        Bitmap image = new Bitmap(stream);

そしてこれは私のxamlコードです

<Image Source="{Binding Source}" HorizontalAlignment="Left"  Height="210" Margin="35,10,0,0" VerticalAlignment="Top" Width="335">
    </Image>

このビットマップ変数をC#コードでこのxamlイメージにバインドするのを手伝ってもらえますか?

4

3 に答える 3

8

XAML 内からではなく、C# コードから設定したい場合は、MSDN リファレンスで詳しく説明されているこの簡単なソリューションを使用する必要があります。

string path = "Resources/Untitled-100000.png";
BitmapImage bitmap = new BitmapImage(new Uri(path, UriKind.Relative));
image.Source = bitmap;

Imageただし、最初に、 C# から参照できるように名前を付ける必要があります。

<Image x:Name="image" ... />

Windows フォーム クラスを参照する必要はありません。イメージをアセンブリに埋め込む必要がある場合は、イメージをロードするために次のより長いコードが必要です。

string path = "SplashDemo.Resources.Untitled-100000.png";
using (Stream fileStream = GetType().Assembly.GetManifestResourceStream(path))
{
    PngBitmapDecoder bitmapDecoder = new PngBitmapDecoder(fileStream,
        BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
    ImageSource imageSource = bitmapDecoder.Frames[0];
    image.Source = imageSource;
}
于 2012-06-30T18:40:16.513 に答える
2

サンプルコードは次のとおりです。

// Winforms Image we want to get the WPF Image from...
System.Drawing.Image imgWinForms = System.Drawing.Image.FromFile("test.png");

// ImageSource ...
BitmapImage bi = new BitmapImage();
bi.BeginInit();
MemoryStream ms = new MemoryStream();

// Save to a memory stream...
imgWinForms.Save(ms, ImageFormat.Bmp);

// Rewind the stream...    
ms.Seek(0, SeekOrigin.Begin);

// Tell the WPF image to use this stream...
bi.StreamSource = ms;
bi.EndInit();

ここをクリックしてリファレンスを表示

于 2012-06-30T18:30:43.607 に答える
0

WPF を使用している場合は、プロジェクトで画像を右クリックし、 を に設定しBuild ActionますResourceMyImage.jpg画像が呼び出され、プロジェクト内のフォルダーにあると仮定すると、C# コードを使用せずResourcesに直接参照できるはずです。xamlこのような:

<Image Source="/Resources/MyImage.jpg" 
    HorizontalAlignment="Left"
    Height="210" 
    Margin="35,10,0,0"
    VerticalAlignment="Top"
    Width="335">
</Image>
于 2012-06-30T18:37:54.260 に答える