【问题标题】:display an image from file in wpf isn't working?在 wpf 中显示文件中的图像不起作用?
【发布时间】:2013-12-28 13:31:41
【问题描述】:

我有一个按钮 b3 和一个名为 pictureBox1 的图像。我正在使用 WPF,但是我使用的是 winforms openFileDialog 而不是 WPF 附带的:

下面是我放在按钮点击事件中的代码:

 private void b3_Click(object sender, RoutedEventArgs e)
    {
        System.Windows.Forms.OpenFileDialog openDialogIcon = new System.Windows.Forms.OpenFileDialog();
        if (openDialogIcon.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
            Image i = new Image();
            BitmapImage src = new BitmapImage();
            src.BeginInit();
            src.UriSource = new Uri(openDialogIcon.FileName, UriKind.Absolute);
            src.CacheOption = BitmapCacheOption.OnLoad;
            src.EndInit();
            i.Source = src;
            i.Stretch = Stretch.Uniform;
            //int q = src.PixelHeight;        // Image loads here

        }
    }

当我单击按钮并选择一个图标时。该图标未出现在pictureBox1 中。

谁能解释一下为什么上面的代码没有显示图片框内的图标?

【问题讨论】:

  • 我看不到你在哪里分配了一些东西给图片框1...
  • 是的。这就是问题所在。抱歉,在发布此问题之前,我不得不进一步研究代码。

标签: c# wpf


【解决方案1】:

您需要将您的图像分配给图片框,否则您不会在屏幕上看到它,并且您只在内存中创建了图像对象。

private void b3_Click(object sender, RoutedEventArgs e)
{
    System.Windows.Forms.OpenFileDialog openDialogIcon = new System.Windows.Forms.OpenFileDialog();
    if (openDialogIcon.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
        BitmapImage src = new BitmapImage();
        src.BeginInit();
        src.UriSource = new Uri(openDialogIcon.FileName, UriKind.Absolute);
        src.CacheOption = BitmapCacheOption.OnLoad;
        src.EndInit();
        pictureBox1.Source = src;
    }
}

【讨论】:

    【解决方案2】:

    尝试将Image 控件拖放到您的窗口中

    ...
    //imageStretch <- the name of Image control
     i.Stretch = Stretch.Uniform;
     //int q = src.PixelHeight;        // Image loads here
     imageStretch.Source = src;
    
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-19
      • 2019-03-18
      • 2019-09-06
      • 1970-01-01
      • 2017-02-18
      • 2010-12-18
      • 2011-09-19
      • 2020-12-15
      相关资源
      最近更新 更多