Windows Phone image not displaying - c#

I'm creating an app which I can select items on combobox to display an image on the screen.
I have 196 png files in /assets/flags/. when I select an item on combobox, the image does not display. There are no errors or exceptions. What am i doing wrong?
private void okBtn_Click(object sender, RoutedEventArgs e)
{
if (myComboBox.SelectedItem.ToString() == "Afghanistan")
{
imageBox.Source =
new BitmapImage(new Uri("ms-appx:///Assets/flags/af.png", UriKind.Absolute));
}
else if (myComboBox.SelectedItem.ToString() == "Danmark")
{
imageBox.Source =
new BitmapImage(new Uri("ms-appx:///Assets/flags/dk.png", UriKind.Absolute));
}
else
{
}
}

You wrote the code inside any Button Click event "okBtn",
Try putting "IF" block inside combobox's default event which is Selection Changed.
Private Sub myComboBox_SelectionChanged(sender As Object, e As Args)
End Sub

well i have solved the problem. the combobox selection must equal to the values and not equal to the strings
if (myComboBox.SelectedIndex == 0)
{
imageBox.Source = new BitmapImage(new Uri("ms-appx:///Assets/flags/af.png", UriKind.Absolute));
}
else if (myComboBox.SelectedIndex == 1)
{
imageBox.Source = new BitmapImage(new Uri("ms-appx:///Assets/flags/dk.png", UriKind.Absolute));
}

Related

Emptying a listbox programmatically

I want to clear listbox everytime when addImages button is clicked which adds new items to it but I am facing problem in clearing it. Following is my code:
private void addImages_Click(object sender, RoutedEventArgs e)
{
FileInfo Images;
string[] filenames = null;
System.Windows.Forms.FolderBrowserDialog folderDlg = new System.Windows.Forms.FolderBrowserDialog();
folderDlg.ShowNewFolderButton = true;
System.Windows.Forms.DialogResult result = folderDlg.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
filenames = System.IO.Directory.GetFiles(folderDlg.SelectedPath);
foreach (string image in filenames)
{
Images = new FileInfo(image);
if(Images.Extension.ToLower() == ".png" || Images.Extension.ToLower() == ".jpg" || Images.Extension.ToLower() == ".gif" || Images.Extension.ToLower() == ".jpeg" || Images.Extension.ToLower() == ".bmp" || Images.Extension.ToLower() == ".tif")
{
ImageList.Items.Add(new LoadImages(new BitmapImage(new Uri(image))));
}
}
}
}
I have tried ImageList.items.clear(), BindingOperations.ClearAllBindings(ImageList) but these removed items first time only when button is clicked next time onwards they don't clear the list. I want list to be cleared everytime when button is clicked.
This code below should work properly. the only thing that might be problematic
private void addImages_Click(object sender, RoutedEventArgs e)
{
ImageList.Items.Clear();
RefreshList();
FileInfo Images;
string[] filenames = null;
System.Windows.Forms.FolderBrowserDialog folderDlg = new System.Windows.Forms.FolderBrowserDialog();
folderDlg.ShowNewFolderButton = true;
System.Windows.Forms.DialogResult result = folderDlg.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
filenames = System.IO.Directory.GetFiles(folderDlg.SelectedPath);
foreach (string image in filenames)
{
Images = new FileInfo(image);
if(new string[]{".png", ".jpg", ".gif", ".jpeg", ".bmp", ".tif"}.Contains(Images.Extension.ToLower()))
{
ImageList.Items.Add(new LoadImages(new BitmapImage(new Uri(image))));
}
}
}
RefreshList();
}
private void RefreshList()
{
// Force visual refresh of control
ImageList.Refresh();
}
*note i cleaned up the extension validation
Edit : I just noticed you talk about Bindings. well you problem is easy then. you cannot clear a list binded to a control. the control will keep original source. You can only UPDATE a binding source otherwise you need to manually update the binding.
Binding on collection is a like a climbing.
Control is the person
Ropes are the DataSource(collection)
Mountain is your model
If in your model you clear (cut) the source (all ropes)
the Control (person) still hold the source (ropes)
If you want the control (person) to have a new source (rope)
You need to add a new one so he can jump on it an remove old ones.
ListBox.Items.Clear should clear the list, if you need that to happen every time the button is clicked then you need it in your event handler i.e.
private void addImages_Click(object sender, RoutedEventArgs e)
{
listBox.Items.Clear();
// do stuff
}
Try this ..
ImageList.Images.Clear();
listBox.Items.Clear();

C# Passing image on select from one page to another xaml page in WindowsPhone

Using Photochooser Task the image has to be loaded and passed immediately to another page. But shows blank when implemented the following code:
private void LoadPicture_Click(object sender, RoutedEventArgs e)
{
PhotoChooserTask photoChooserTask;
photoChooserTask = new PhotoChooserTask();
photoChooserTask.Completed += new EventHandler<PhotoResult>(photoChooserTask_Completed);
photoChooserTask.Show();
NavigationService.Navigate(new Uri("/Page1.xaml", UriKind.Relative));
}
void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
bmp.SetSource(e.ChosenPhoto);
Page1 p1 = new Page1();
p1.encodeImg.Source = bmp;
}
else
{
MessageBox.Show("Image Loading Failed.");
}
}
Please suggest in fixing the above the issue.
Thanks!
Have you solved it? if you haven't you could use something like this. in your photoChooseTask handler save the bitmapImage
PhoneApplicationService.Current.State["yourparam"] = bmp;
and then in your Page1 you get the bitmapImage
BitmapImage bitmapGet = PhoneApplicationService.Current.State["yourparam"] as BitmapImage;
here's how you should use this.
void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
bmp.SetSource(e.ChosenPhoto);
//save the bitmapImage
PhoneApplicationService.Current.State["yourparam"] = bmp;
}
else
{
MessageBox.Show("Image Loading Failed.");
}
NavigationService.Navigate(new Uri("/Page1.xaml", UriKind.Relative));
}
your Page1
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
//get the bitmapImage
BitmapImage bitmapGet = PhoneApplicationService.Current.State["yourparam"] as BitmapImage;
//set the bitmpaImage
img.Source = bitmapGet;
base.OnNavigatedTo(e);
}
More about PhoneApplicationService.Current.State :)
The navigation must be done after completed event, photochooser.show() suppresses the main application thread, hence you can only pass the image stream once you get it. So, shift navigation statement to completed event handler and using isolatedstoragesettings.applicationsettings to store the image and get it back on second page.
Another way to achieve it is to save the image in isolateStorage first and pass the file path to your page1 as a string parameter.
page1 then could load the image anytime it needs.

'A generic error occurred in GDI+' when saving an image

I have been having quite a problem with this.
Here is my code.
int frame = 0;
//This is a wpf button event
private void up_Click(object sender, RoutedEventArgs e)
{
frame++;
LoadPic();
}
private void LoadPic()
{
string fn = #"C:\Folder\image" + (frame % 2).ToString() + ".png";
Bitmap bmp = new Bitmap(302, 170);
bmp.Save(fn);
bmp.Dispose();
//Picebox is a wpf Image control
Picbox.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri(fn));
}
private void down_Click(object sender, RoutedEventArgs e)
{
frame--;
LoadPic();
}
When I start the program, a wpf window pops open. There are two buttons with the events shown in the code.
When I press the up button twice it works fine. This saves two PNGs to the locations
"C:\Folder\image0.png" and "C:\Folder\image1.png"
The third time I press the button, it should save it to "C:\Folder\image0.png" again.
Instead, it gives the exception 'A generic error occurred in GDI+'.
I have had a similar problem before, and solved it by adding these two lines:
GC.Collect();
GC.WaitForPendingFinalizers();
It didn't work this time.
To avoid the filelock that BitmapImage creates you have to take care of a bit more initialization. According to this question here on SO, it can be done like this (ported to C# from their VB.Net code).
private void LoadPic()
{
string fn = #"C:\Folder\image" + (frame % 2).ToString() + ".png";
Bitmap bmp = new Bitmap(302, 170);
bmp.Save(fn);
bmp.Dispose();
var img = new System.Windows.Media.Imaging.BitmapImage();
img.BeginInit();
img.CacheOption = System.Windows.Media.Imaging.BitmapCacheOption.OnLoad;
img.UriSource = new Uri(fn);
img.EndInit();
Picbox.Source = img;
}

how to display image in a grid using C# for WP8?

i need to insert an image in a WP8. i have a stack of images. once i click the image, it has to be set as background for a grid. so i created an empty "grid1" and button. wrote the below code in the button click event, but the image doesnot get displayed !
private void bg6_Click(object sender, RoutedEventArgs e)
{
System.Windows.Media.ImageBrush myBrush = new System.Windows.Media.ImageBrush();
Image image = new Image();
image.Source = new System.Windows.Media.Imaging.BitmapImage(
new Uri("\\PhoneApp2\\PhoneApp2\\Assets\\bg\\bg5.jpg"));
myBrush.ImageSource = image.Source;
// Grid grid1 = new Grid();
grid1.Background = myBrush;
}
It is hard to know if your image file is in the correct place and set to the right build type. I'd suggest adding an event handler to the Image failed event.
private void bg6_Click(object sender, RoutedEventArgs e)
{
System.Windows.Media.ImageBrush myBrush = new System.Windows.Media.ImageBrush();
Image image = new Image();
image.ImageFailed += (s, e) => MessageBox.Show("Failed to load: " + e.ErrorException.Message);
image.Source = new System.Windows.Media.Imaging.BitmapImage(
new Uri("\\PhoneApp2\\PhoneApp2\\Assets\\bg\\bg5.jpg"));
myBrush.ImageSource = image.Source;
// Grid grid1 = new Grid();
grid1.Background = myBrush;
}
First, you don't need to use Image to fill the background from URI.
private void bg6_Click(object sender, RoutedEventArgs e)
{
System.Windows.Media.ImageBrush myBrush = new System.Windows.Media.ImageBrush(new Uri("\\PhoneApp2\\PhoneApp2\\Assets\\bg\\bg5.jpg"));
// Grid grid1 = new Grid();
grid1.Background = myBrush;
}
Second, it is a WAY better to design it in XAML and manipulate it visibility and source from code by creating the helper class with visibility and source property. Don't forget to implement INotifyPropertyChanged interface into that class.
<Grid x:Name="myGrid" DataContext="{Binding}" Visibility="{Binding Path=VisibleProperty}">
<Grid.Background>
<ImageBrush x:Name="myBrush" ImageSource="{Binding Path=SourceProperty}"></ImageBrush>
</Grid.Background>
And in code:
private void bg6_Click(object sender, RoutedEventArgs e)
{
myGrid.DataContext=new myImagePresenterClass(new Uri("\\PhoneApp2\\PhoneApp2\\Assets\\bg\\bg5.jpg"), Visibility.Visible)
}
public class myImagePresenterClass:INotifyPropertyChanged
{
private URI sourceProperty
Public URI SourceProperty
{
get
{
return sourceProperty;
}
set
{
sourceProperty=value;
if(PropertyChanged!=null){PropertyChanged(this, new PropertyChangedEventArgs("SourceProperty"));}
}
}
//Don't forget to implement the Visible property the same way as SourceProperty and the class constructor.
}
i found the mistake... i'm sorry guys. i didn't follow the syntax correctly. i missed the '#' in the Uri method. the correct way to represent this is
private void bg1_Click(object sender, RoutedEventArgs e)
{
System.Windows.Media.ImageBrush myBrush = new System.Windows.Media.ImageBrush();
Image image = new Image();
image.ImageFailed += (s, i) => MessageBox.Show("Failed to load: " + i.ErrorException.Message);
image.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri(#"/Assets/bg/bg1.jpg/", UriKind.RelativeOrAbsolute));
myBrush.ImageSource = image.Source;
grid1.Background = myBrush;
}

Error in changing the background dynamically

First i've created a button(named as BackgroundChooser) that is used to change the background image dynamically(they can select their own image as background). But i have already used a default background image(image1.jpg) for my windows phone 7 application. When i click on the choose background button, it directs to our saved pictures. After that i have selected am image as my own background image. But the default background image is still doesn't changed.
Then when i have changed the default background to black, then i can set my own background image(it's working perfectly). Need help!!! Thanks in advance for your hard work!!!
Below is the code i have used-:
private void BackgroundChooser_Click(object sender, MouseEventArgs e)
{
var PhotoChooser = new PhotoChooserTask();
PhotoChooser.Completed += new EventHandler<PhotoResult(PhotoChooser_Completed);
PhotoChooser.Show();
}
void PhotoChooser_Completed(object sender, PhotoResult e)
{
{
if (e.TaskResult == TaskResult.OK)
{
System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
bmp.SetSource(e.ChosenPhoto);
var app = Application.Current as App;
if (app == null)
return;
var imageBrush = new ImageBrush { ImageSource = bmp, Opacity = 0.5d };
app.RootFrame.Background = imageBrush;
//app.RootFrame.Background = new SolidColorBrush(Colors.Black); //we can apply just color too like this
}
}
}
instead of app.RootFrame.Background, try setting the Background property on some display object on your page such as myPanoramaControl.Background = imageBrush; or LayoutRoot.Background = imageBrush; (where LayoutRoot is the name of the default grid control for a new WP Page)

Categories