如何在弹出控件中打开特定的 JPEG 图像?

How to open a specific JPEG image inside a popup control?

我正在使用 WPF 和 C# 创建拼图应用程序。

我正在尝试通过 OpenFileDialog 选择 JPEG 图像在弹出窗口中打开照片 class。

我目前面临的问题是弹出窗口中没有显示任何内容(未选择图像),我不知道是否应该在 XAML 文件中添加标签,因为我不知道'知道确切的来源是什么(因为来源会根据打开的图像而改变)。

这是 .cs 文件中的代码:

private void Open_Click(object sender, RoutedEventArgs e)
    {
        PatternWindow.IsOpen = true;

        Microsoft.Win32.OpenFileDialog openFileDialong1 = new Microsoft.Win32.OpenFileDialog();
        openFileDialong1.Filter = "Image files (.jpg)|*.jpg";
        openFileDialong1.Title = "Open an Image File";
        openFileDialong1.ShowDialog();
        string fileName = openFileDialong1.FileName;
        try
        {
            System.Drawing.Image image = System.Drawing.Image.FromFile(fileName);
        }
        catch (Exception ex)
        {
        }
    }

这是我的 XAML 文件中的代码,用于显示 UI 代码:

             <StackPanel>
                <Popup Name="PatternWindow" PlacementTarget="{Binding ElementName=ButtonCanvas}" Placement="Relative" HorizontalOffset="280" VerticalOffset="50" IsOpen="False" Width="250" Height="250">
                    <Border BorderBrush="Blue" BorderThickness="5"  Background="White">
                        <StackPanel>
                            <TextBlock Foreground="Black" FontSize="16">Chosen Pattern Window</TextBlock>
                            <Image Name="patternImage" Source= Width="200" Height="200"/>

                        </StackPanel>
                    </Border>
                </Popup>
            </StackPanel>

如有任何帮助,我们将不胜感激。

对于UI,您不需要在图片标签中写入源:

<Image Name="patternImage" Width="200" Height="200"/>

而对于代码,您需要从所选文件创建 BitmapImage:

    private void Open_Click(object sender, RoutedEventArgs e)
    {
        PatternWindow.IsOpen = true;

        Microsoft.Win32.OpenFileDialog openFileDialong1 = new Microsoft.Win32.OpenFileDialog();
        openFileDialong1.Filter = "Image files (.jpg)|*.jpg";
        openFileDialong1.Title = "Open an Image File";
        openFileDialong1.ShowDialog();
        string fileName = openFileDialong1.FileName;
        try
        {
            //here you create a bitmap image from filename
            BitmapImage bi = new BitmapImage();
            bi.BeginInit();
            bi.CacheOption = BitmapCacheOption.OnLoad;
            bi.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
            bi.UriSource = new Uri(fileName);
            bi.EndInit();
            patternImage.Source = bi;
        }
        catch (Exception ex)
        {
           //throw exception
        }
    }

wpf 图像控件将在给定路径的情况下工作,您尝试过吗...

patternImage.Source = new BitmapSource(new Uri(文件名));

...在您的事件处理程序中?

根据反馈进行编辑