Wednesday, October 01, 2008

MSDN Question on WPF : Display Image XAML without copy/paste

As a part of personal development, I have once again started answering questions on forums. I was once a top contributor at dotnetforums.com but the site is no longer up. From what I learnt back then, I strongly believe that you get to learn more by answering people's questions online. As a part of it, I decided I would write a little about every answer that I give on windowsclient.net, if it is marked as answer. So, here comes the first post. One member had company logo exported as XAML. Now he wants the logo to show up inside an Image element, without having to paste the XAMl at all the places.

Question: Is there a way to display the contents of this file inside an <Image> element, therefore without copying/pasting the file content?

My suggestion (definitely not perfect):
Give the Image a name. Modify the XAML you got into a drawing image root and save it as a resource. Load the XAML at runtime from the resource and use XamlReader.Load("your xaml"). It now returns DrawingImage and set it to the source of the actual image. So, it would look something like this.

DrawingImage img = XamlReader.Load("mylogo.xaml") as DrawingImage;

Set this "img" as Source for the Image element.

where mylogo.xaml would be like:

<DrawingImage xmlns="wpf namespace...">

<!-- Xaml for your image, that fits in as a child for DrawingImage -->

</DrawingImage>

No comments: