I'm working with WPF and C# to create a puzzle application.
I am trying to open a photo in a popup by selecting a JPEG image via the OpenFileDialog class.
The problem that I'm facing currently is nothing shows up in the popup (no selected image) and I don't know if I should actually be having an tag in the XAML file because I don't know what the exact source for that would be (as the source would change depending on which image is opened).
Here is my code from the .cs file :
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)
{
}
}
Here is my code from the XAML file to show UI code:
<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>
Any help would be much appreciated.
For UI, you don't need to write the Source in Image tag:
<Image Name="patternImage" Width="200" Height="200"/>
while for the code, you need to create BitmapImage from the selected file:
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
}
}