我正在使用WPF和C#创建一个拼图应用程序。
我试图通过OpenFileDialog类选择JPEG图像来弹出一张照片。
我目前面临的问题是弹出窗口中没有显示(没有选定的图像),我不知道我是否应该在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>
非常感谢任何帮助。
答案 0 :(得分:2)
对于UI,您无需在Image标记中编写Source:
<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
}
}
答案 1 :(得分:-1)
wpf图像控件将在给定路径的情况下工作,你试过......
patternImage.Source = new BitmapSource(new Uri(file name));
...在您的事件处理程序中?
根据反馈进行编辑