欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

WPF Image绑定Xaml

程序员文章站 2022-06-08 23:04:55
...
<Window x:Class="CityMangeLogin.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:CityMangeLogin"
        mc:Ignorable="d"
        Title="MainWindow" Height="400" Width="400">
    <Window.Resources>
        <local:ImageConvert x:Key="Imgconvert" />
    </Window.Resources>
    <StackPanel>
    <StackPanel Orientation="Horizontal" >
        <Image Width="40" Height="30"  Stretch="Fill" 
               Source="{Binding ImageSource,Converter={StaticResource Imgconvert }}" ></Image>
        <Button Command="{Binding GetImgCommand}" Content="刷新验证"/>
    </StackPanel>     
    </StackPanel>
   
</Window>

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Media.Imaging;

namespace CityMangeLogin
{
    public class ImageConvert : IValueConverter
    {
        /// <summary>
        /// 转换图片
        /// </summary>
        /// <param name="value"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            BitmapImage imageSource = null;
            Image img = (Image)value;
            if (img != null)
            {
                imageSource = new BitmapImage();
                imageSource.BeginInit();
                ImageConverter imgconv = new ImageConverter();
                byte[] buffer = (byte[])imgconv.ConvertTo(img, typeof(byte[]));
                imageSource.StreamSource = new MemoryStream(buffer);
                imageSource.EndInit();

            }
            return imageSource;

        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

相关标签: WPF