Binding an Image in WPF?
Solution 1
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;
}
}
}
Solution 2
If you have a path to your image and just want to be able to change the image on the fly, then bind to a dependency property of type string and in your method, set the value of the dependency property.
<Image Source="{Binding MyImagePath}" />
public static readonly DependencyProperty MyImagePathProperty = DependencyProperty.Register("MyImagePath", typeof(string), typeof(ClassName), new PropertyMetadata("pack://application:,,,/YourAssembly;component//icons/icon1.png"));
public string MyImagePath
{
get { return (string)GetValue(MyImagePathhProperty); }
set { SetValue(MyImagePathProperty, value); }
}
Comments
-
Ricardo Sampaio almost 2 years
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. -
Ricardo Sampaio about 14 yearsObjectDataProvider is Static, but I'm gonna do it Dynamic !