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

时间:2016-03-01 16:45:09

标签: c# wpf database data-binding wpf-controls

我正在创建一个程序,这里基本上都是它的所有代码。这个想法很简单,当有人点击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;
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

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

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方法。你在邮政编码之前剪了吗?因为如果你没有它,你的代码将无法编译。

如果你决定使用View Model,你可以这样做:

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

设置datacontext:

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

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