Link image in WPF?

I want to show the image in WPF created by the process,
for example: we have a method called createWPFImage ()

Image createWPFImage() { ... }

So, the output of createWPFImage () is the image.
In the XAML code, we have 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 an image in XAML code?
I would appreciate it if you would guide me.

+3
source share
2 answers

Say you have a class "MyClass" using the "CreateWpfImage" method (see example below).

XAML MyClass, CreateWpfImage, ObjectDataProvider "" (. Bea Stollnitz 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>

MyClass XAML -

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;
        }
    }
}
+4

, , .

<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); }
    }
+2

Source: https://habr.com/ru/post/1731366/


All Articles