WPF 不显示任何图像.为什么

本文关键字:图像 为什么 任何 显示 WPF | 更新日期: 2023-09-27 18:36:51

我正在创建一个程序,这里基本上都是代码。这个想法很简单,当有人点击button_ok_Click时,我想显示他们的名字和照片(基于他们插入的数字)。每件事都很好,除了我尝试过但没有成功的事情:当有人点击button_ok_Click时显示我数据库中的图像。感谢您的帮助。

<Image x:Name="image" HorizontalAlignment="Left" Height="386" Margin="480,120,0,0" VerticalAlignment="Top" Width="259" Source="{Binding Path=ImageFunc, Converter={StaticResource BinaryImageConverter}}"/>

namespace WpfApplication1
{
    class FuncionarioDAO : IFuncionarioDAO
    {
        private DbConnection conn;
        private Exception erro;
        private string sql;
        public FuncionarioDAO()
        {
            try
            {
                this.conn = DAOConexaoFactory.getConexao(3, "TEST", "TEST");
            }
            catch
            {
                erro = DAOConexaoFactory.getErro();
            }
        }
        public Funcionario buscaFuncionario(string id)
        {
            Funcionario funcionario = new Funcionario();
            sql = "SELECT CHAPA, NOME, IMAGEM FROM TABLE WHERE CHAPA='"+id+"'";
            try
            {
                // Cria Conexão Driver especifico
                DbCommand cmd = DAOConexaoFactory.getFactory().CreateCommand();
                cmd.Connection = conn;
                cmd.CommandText = sql;
                cmd.ExecuteNonQuery();
                // Cria set de dados
                DbDataReader dados = cmd.ExecuteReader();
                // Converte Decimal para Double para IBM DB2 e MSSQL
                if (dados.HasRows)
                {
                    while (dados.Read())
                    {
                        funcionario.Mat = dados.GetString(0);
                        funcionario.Nome = dados.GetString(1);
                        funcionario.ImageFunc = (byte[]) dados["IMAGEM"];
                    }
                }
            }
            catch (Exception ex)
            {
                // Retorna erro
                erro = ex;
            }
            return funcionario; 
        }
        public bool insereFuncionario(Funcionario funcionario)
        {
            throw new NotImplementedException();
        }
        public string getErro()
        {
            return erro.ToString();
        }

    }
}

namespace WpfApplication1
{
    class Funcionario
    {
        private string mat;
        private string nome;
        private byte[] imagemFunc;
        public Funcionario()
        {
        }
        public Funcionario(string mat)
        {
            this.mat = mat;
        }
        public Funcionario(string mat, string nome, byte[] imagemFunc)
        {
            this.mat = mat;
            this.nome = nome;
            this.imagemFunc = imagemFunc;
        }
        public string Mat { get; set; }
        public string Nome { get; set; }
        public byte[] ImageFunc { get; set; }
    }
}

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void button1(object sender, RoutedEventArgs e)
        {
            textBox.Text = textBox.Text + "1";
        }
        private void button_2_Click(object sender, RoutedEventArgs e)
        {
            textBox.Text = textBox.Text + "2";
        }
        private void button_3_Click(object sender, RoutedEventArgs e)
        {
            textBox.Text = textBox.Text + "3";
        }
        private void button_4_Click(object sender, RoutedEventArgs e)
        {
            textBox.Text = textBox.Text + "4";
        }
        private void button_5_Click(object sender, RoutedEventArgs e)
        {
            textBox.Text = textBox.Text + "5";
        }
        private void button_6_Click(object sender, RoutedEventArgs e)
        {
            textBox.Text = textBox.Text + "6";
        }
        private void button_7_Click(object sender, RoutedEventArgs e)
        {
            textBox.Text = textBox.Text + "7";
        }
        private void button_8_Click(object sender, RoutedEventArgs e)
        {
            textBox.Text = textBox.Text + "8";
        }
        private void button_9_Click(object sender, RoutedEventArgs e)
        {
            textBox.Text = textBox.Text + "9";
        }
        private void button_0_Click(object sender, RoutedEventArgs e)
        {
            textBox.Text = textBox.Text + "0";
        }
        private void button_erase_Click(object sender, RoutedEventArgs e)
        {
            textBox.Text = "";
        }
        private void button_ok_Click(object sender, RoutedEventArgs e)
        {
            Funcionario funcionario = new FuncionarioDAO().buscaFuncionario(textBox.Text);
            textBox2.Text = funcionario.Nome.Substring(0,funcionario.Nome.IndexOf(" "));

        }
    }
}

    namespace WpfApplication1
    {
        class BinaryImageConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                    byte[] ByteArray = value as byte[];
                    BitmapImage bmp = new BitmapImage();
                    bmp.BeginInit();
                    bmp.StreamSource = new MemoryStream(ByteArray);
                    bmp.EndInit();
                    return bmp;
            }
        }
    }

WPF 不显示任何图像.为什么

您似乎不使用视图模型,因此可以直接将位图设置为图像:

private void button_ok_Click(object sender, RoutedEventArgs e)
{
    Funcionario funcionario = new FuncionarioDAO().buscaFuncionario(textBox.Text);
    textBox2.Text = funcionario.Nome.Substring(0,funcionario.Nome.IndexOf(" "));
    using (var stream = new MemoryStream(funcionario.ImageFunc))
    {
        BitmapImage bmp = new BitmapImage();
        bmp.BeginInit();
        bmp.CacheOption = BitmapCacheOption.OnLoad;
        bmp.StreamSource = stream;
        bmp.EndInit();
        image.Source = bmp;
    }
    // If you don't see image, perhap your image is invalid
    // Save it to a file and open this file in Windows Explorer to check
    File.WriteAllBytes("D:''img.jpg", funcionario.ImageFunc);
}

这里不需要 IValueConverter。您需要从映像中删除以下内容:

...Source="{Binding Path=ImageFunc, Converter={StaticResource BinaryImageConverter}}"...

顺便说一句,您的BinaryImageConverter缺乏ConvertBack方法。你在这里的邮政编码之前剪掉它吗?因为如果你没有它,你的代码就不会遵守。

如果您决定使用视图模型,则可以执行以下操作:

ConvertBack方法添加到您的BinaryImageConverter

public class BinaryImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        byte[] ByteArray = value as byte[];
        BitmapImage bmp = new BitmapImage();
        using (var stream = new MemoryStream(ByteArray))
        {
            bmp.BeginInit();
            bmp.CacheOption = BitmapCacheOption.OnLoad;
            bmp.StreamSource = stream;
            bmp.EndInit();
        }
        return bmp;
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return null;
    }
}

设置数据上下文:

private void button_ok_Click(object sender, RoutedEventArgs e)
{
    Funcionario funcionario = new FuncionarioDAO().buscaFuncionario(textBox.Text);
    DataContext = funcionario;
    // If textBox2.Text bind to Funcionario you can remove bellow line, move IndexOf to buscaFuncionario function
    textBox2.Text = funcionario.Nome.Substring(0,funcionario.Nome.IndexOf(" "));
}

最后,正如@Bearcat9425所说,您不应该使用 String.Concat 进行数据库查询。