Binding an Image in WPF?

c#, data-binding, image, wpf

Solution

Say you have class "MyClass" with method "CreateWpfImage" (see example below).

In your XAML you can create MyClass, and then call CreateWpfImage, using ObjectDataProvider in a Resources section (See Bea Stollnitz blog article ObjectDataProvider).

XAML

<Window x:Class="MyApplicationNamespace.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:MyApplicationNamespace="clr-namespace:MyApplicationNamespace"
    Title="Window1" Height="300" Width="300">       

<Window.Resources>
    <ObjectDataProvider ObjectType="{x:Type MyApplicationNamespace:MyClass}" x:Key="MyClass" />
    <ObjectDataProvider ObjectInstance="{StaticResource MyClass}" MethodName="CreateWpfImpage" x:Key="MyImage" />
</Window.Resources>

<StackPanel>
    <Image Source="{Binding Source={StaticResource MyImage}, Path=Source}"/>
</StackPanel>

Example MyClass code to create an image for the XAML to use -

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace MyApplicationNamespace
{
    public class MyClass
    {
        public Image CreateWpfImpage()
        {
            GeometryDrawing aGeometryDrawing = new GeometryDrawing();
            aGeometryDrawing.Geometry = new EllipseGeometry(new Point(50, 50), 50, 50);
            aGeometryDrawing.Pen = new Pen(Brushes.Red, 10);
            aGeometryDrawing.Brush = Brushes.Blue;
            DrawingImage geometryImage = new DrawingImage(aGeometryDrawing);

            Image anImage = new Image();
            anImage.Source = geometryImage;
            return anImage;
        }
    }
}

Problem

I wanna show an image in WPF that is created by a process, e.g : we have a method that is named createWPFImage() ``` Image createWPFImage() { ... } ``` So, the output of createWPFImage() is an Image. In the XAML code, we have a something like below : ``` <StackPanel.ToolTip> <StackPanel Orientation="Horizontal"> <Image Width="64" Height="64" Margin="0 2 4 0" /> <TextBlock Text="{Binding Path=Description}" VerticalAlignment="Center" /> </StackPanel> </StackPanel.ToolTip> ``` Now, How can I bind the output of createWPFImage() to the Image in XAML code ? I would be appreciate if you guide me.

Original source