use*_*114 3 c# xaml bind bitmap
我有位图图像变量,我想将它绑定到我的 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);
Run Code Online (Sandbox Code Playgroud)
这是我的 xaml 代码
<Image Source="{Binding Source}" HorizontalAlignment="Left" Height="210" Margin="35,10,0,0" VerticalAlignment="Top" Width="335">
</Image>
Run Code Online (Sandbox Code Playgroud)
你能帮我通过 C# 代码将此位图变量绑定到这个 xaml 图像吗?
如果你真的想从 C# 代码而不是从 XAML 内部设置它,你应该使用MSDN 参考中进一步描述的这个简单的解决方案:
string path = "Resources/Untitled-100000.png";
BitmapImage bitmap = new BitmapImage(new Uri(path, UriKind.Relative));
image.Source = bitmap;
Run Code Online (Sandbox Code Playgroud)
但首先,您需要提供Image一个名称,以便您可以从 c# 中引用它:
<Image x:Name="image" ... />
Run Code Online (Sandbox Code Playgroud)
无需引用 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;
}
Run Code Online (Sandbox Code Playgroud)