[英]Bind Xaml bitmap image
我有位圖圖像變量,我想將其綁定到我的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圖像嗎?
如果您真的想從C#代碼而不是從XAML內部進行設置,則應使用在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;
}
這是一些示例代碼:
// 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();
如果您使用的是WPF,請在項目中右鍵單擊圖像,然后將Build Action
設置為Resource
。 假設您的圖像稱為MyImage.jpg
,並且位於項目的Resources
文件夾中,則應該能夠在xaml
直接引用它,而無需使用任何C#代碼。 像這樣:
<Image Source="/Resources/MyImage.jpg"
HorizontalAlignment="Left"
Height="210"
Margin="35,10,0,0"
VerticalAlignment="Top"
Width="335">
</Image>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.