2010-02-04 74 views
3

我想告诉在WPF的图像由一个进程创建,
e.g:我们有一个名为createWPFImage()方法
在WPF中绑定图像?

Image createWPFImage() { ... } 

所以,createWPFImage的输出()是图像。
在XAML代码中,我们有一个类似如下:

<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> 


现在,我怎样才能createWPFImage()的输出绑定到XAML代码的形象呢?
如果你指导我,我将不胜感激。

+0

你是什么意思的“绑定”的方法?在WPF中,“绑定”是指在源值更改时更改目标值(反之亦然;除了一次性绑定)。或者你只是想将方法的输出设置为图像?该方法是否根据不同的条件返回不同的输出?你有没有尝试过使用依赖项属性? – mg007 2010-02-04 16:19:27

回答

4

假设你有类 “myclass” 的方法 “CreateWpfImage”(见下面的例子)。

在您的XAML中,您可以创建MyClass,然后在Resources部分中使用ObjectDataProvider调用CreateWpfImage(请参阅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; 
     } 
    } 
} 
+0

ObjectDataProvider是静态的,但我要做到动态! – 2010-02-05 06:01:07

2

如果你有你的形象的路径,只是希望能够要动态更改图像,然后绑定到字符串类型的依赖项属性,并在您的方法中设置依赖项属性的值。

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