Accessing binary resources in code
Accessing binary resources in XAML is very simple, but there is an option to read a binary resource from the code behind. In this recipe, we will learn how to read a binary resource in code and set it in the UI. We will be using an image as an example.
Getting ready
Open your Visual Studio IDE. Let's begin with creating a new WPF project called CH07.BinaryResourceFromCodeDemo
.
How to do it...
Follow these steps to read an image file, embedded as a Resource
, and display it in the UI:
- First, create a folder named
Images
inside the project and add an image inside it. Let's name the imageimage1.png
. - Open the
MainWindow.xaml
file by navigating toSolution Explorer
. - Add an image tag inside the
Grid
panel and name itimg
:
<Grid> <Image x:Name="img" /> </Grid>
- Go to the
MainWindow.xaml.cs
file and, inside the constructor of the class, just after theInitializeComponent()
call, create thestreamResourceInfo
from the resource stream of the image....