我有位图图像变量,我想将它绑定(bind)到我的 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# 代码将此位图变量绑定(bind)到此 xaml 图像吗?
最佳答案
如果您确实想从 C# 代码而不是从 XAML 内部设置它,您应该使用这个简单的解决方案 described further on the MSDN reference :
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;
}
关于c# - 绑定(bind)Xaml位图图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11276438/