开发者

Display WinForm Image in WPF application

I have a dll with quite a bit of System.Drawing.Image resources that I have wrapped into static properties so I can update them dynamically.

I would like to use the images through xaml in a WPF application, but the only way I can figure 开发者_StackOverflow中文版is to do it through the code behind manually.

Is there a way to do the winform to wpf image convertion on a static property in xaml?


You could bind to your images directly, using a converter. Here is an example in a window:

<Window.Resources>
   <WinForms2WPFImageConverter x:Key="WF2WPFDrawingConverter" />
</Window.Resources>

...

This SO question has a drawing converter, which I adapted here as a ValueConverter.

public class WinForms2WPFImageConverter : IValueConverter {

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {

        System.Drawing.Image i = (System.Drawing.Image) value;   
        using (MemoryStream drawingStream = new MemoryStream())
        {

            i.Save(drawingStream);

            i.Seek(0, SeekOrigin.Begin);

            return System.Windows.Media.Imaging.BitmapFrame.Create(drawingStream);
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
            throw new InvalidOperationException();
    }
}

Of course, you need to account for namespaces in the declaration of the resource.

I advise not using static properties, in order to leverage INotifyPropertyChanged (or dependency properties), so that the display automatically changes when the properties point to other images.

(note: this was typed, not copied from VS, so there may be a syntax error somewhere.)


You could bind to your images using a Method in WPF. Here is an example in a link

http://microsoftdotnetsolutions.blogspot.com/2016/07/convert-winforms-image-to-wpf.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜