在wpf中显示文件中的图像不起作用?

时间:2013-12-28 13:31:42

标签: c# wpf

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

下面是我在按钮的click事件中输入的代码:

 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中。

有人可以解释为什么上面的代码没有在pictureBox中显示图标吗?

2 个答案:

答案 0 :(得分:0)

你需要将你的图像分配到pictureBox,否则你不会在屏幕上看到它而你只在内存中创建了图像对象。

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

答案 1 :(得分:0)

尝试在窗口中拖放Image控件

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

...