c# - 绑定(bind)Xaml位图图像

标签 c# xaml bitmap bind

我有位图图像变量,我想将它绑定(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/

相关文章:

c# - 禁用.NET中Treeview中根节点的折叠事件

c# - 使用 Entity Framework 5 从 oracle 包导入程序

c# - 我可以在某些情况下关闭模拟吗

c# - 将图像加载到 wp7 中的应用程序栏

c# - .NET Bitmap.Load 方法在不同的计算机上产生不同的结果

c# - Expression.Call "Contains"方法抛出 "Ambiguous match found exception"

c# - 有没有一种好方法将 xaml 绑定(bind)到依赖于多个其他属性的属性?

c# - 在MVVM中处理MouseEnter over命令

android - Adapter中Bitmaps的异步下载,重点在Bitmap.recycle()

android - 使用 Path.lineTo 在 x 轴上增加一个小数点