How to display images in ListView in Win8 - c#

The problem:
There is no images being displayed.Please help to correct my mistake. Thanks
1) I have stored the photo in a folder called Images and marked the photo as content
2) I have created a class and added it in the project
class ModelImage
{
public string Image_Name { get; set; }
public string Image { get; set; }
public string Description { get; set; }
}
3) I have added the ListView and a Button in MainPage
<ListView Name="LV" ItemsSource="{Binding}" HorizontalAlignment="Left" Height="552" Margin="693,27,0,0" Grid.Row="1" VerticalAlignment="Top" Width="582">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="30" Text="Hello">
<Image Source="{Binding Image}" Height="300" Width="300">
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
--- Button
private void Button_Click_1(object sender, RoutedEventArgs e)
{
List <ModelImage> list = new List <ModelImage>();
{
new ModelImage { Image_Name = "Meat", Image = "/Images/Meat_ProkChop.jpg", Description = "Pork Chop" };
new ModelImage { Image_Name = "Meat", Image = "/Images/Meat_Beef.jpg", Description = "Beef" };
};
LV.DataContext = list;
}
Do I need to use the hardcode Path for the photo inside the folder called Images?

Try "ms-appx:///Images/Image.jpg" instead of "/Images/Image.jpg". Getting the path right is important. Since it is default, this is likely correct already, but ensure your images are marked as "Content" in properties.
Best of luck!

Related

WPF: How to upload an image to your project and use it later on as a resource

I'm studying WPF at school but I ran into a problem with uploading a new image to my project.
The goal is to be able to add an image (at runtime) using a file browser. This image should be uploaded into the project and the filename should be saved in a database. Than it should be accessible as a resource in the project so I can show the image in a listbox for example.
This is what I've got so far:
View where the upload happens:
<Image Height="70px" Source="{Binding newImg}"/>
<Button Height="23" Name="btnLoad" VerticalAlignment="Bottom"
Width="75" Grid.Column="0" Grid.Row="1" Command="{Binding ImgUploadCommand}">_Browse</Button>
ViewModel UploadView
private string fullPath;
private BitmapImage image;
private Patient newPatient = new Patient();
private void KoppelenCommands()
{
FotoUploadCommand = new BaseCommand(FotoPatientUpload);
PatientOpslaanCommand = new BaseCommand(PatientOpslaan);
}
public ICommand FotoUploadCommand { get; set; }
public ICommand PatientOpslaanCommand { get; set; }
public void FotoPatientUpload()
{
OpenFileDialog op = new OpenFileDialog();
op.Title = "Select a picture";
op.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +
"JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
"Portable Network Graphic (*.png)|*.png";
if (op.ShowDialog() == true)
{
image= new BitmapImage(new Uri(op.FileName));
fullPath = op.FileName;
string[] partsFileName = fullPath.Split('\\');
System.Windows.MessageBox.Show(delenFileName[(partsFileName.Length - 1)]);
NewPatient.Image= partsFileName[(delenFileName.Length - 1)];
}
}
public void PatientOpslaan()
{
string destinationPath = GetDestinationPath(NewPatient.Afbeelding, "\\assets\\images");
File.Copy(fullPath, destinationPath, true);
//dataservice (My DS works fine, I can see the correct filename in the database but I save only the name not the Path)
PatientDataService patientDS =
new PatientDataService();
patientDS.InsertPatient(NewPatient);
}
else
{
MessageBox.Show("Niet alle velden zijn ingevuld! Een nieuwe patient moet tenminste een naam en een voornaam krijgen!", "Fout!", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
//opslaan foto in opgegeven map <<Code afkomstig van stackoverflow auteur: Yashpal Singla>>
private static String GetDestinationPath(string filename, string foldername)
{
String appStartPath = System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
appStartPath = String.Format(appStartPath + "\\{0}\\" + filename, foldername);
return appStartPath;
}
The image is correctly saved to the bin/debug/assets/images folder but not as a resource. Because it isn't saved as a resource I can't use it in my MainWindow View which looks like this:
<ListBox HorizontalContentAlignment="Center" ItemsSource="{Binding Patienten}" SelectedItem="{Binding SelectedPatient}" Grid.Column="0" Grid.Row="0">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Name="ImageNameListBox" Visibility="Collapsed"
Text="{Binding Image, StringFormat=../assets/images/{0}}" />
<Border Style="{StaticResource imageBorderStyle}" Grid.Column="0" Grid.Row="0" Height="80px" Width="80px">
<Rectangle Margin="1,-2,-2,1" Height="80px" Width="80px">
<Rectangle.Fill>
<ImageBrush ImageSource="{Binding Text, ElementName=ImageNameListBox}"/>
</Rectangle.Fill>
</Rectangle>
</Border>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
MainWindow ViewModel:
class MainWindowViewModel : BaseViewModel
{
private DialogService dialogService;
private ObservableCollection<Patient> patienten;
public ObservableCollection<Patient> Patienten
{
get
{
return patienten;
}
set
{
patienten = value;
NotifyPropertyChanged();
}
}
private Patient selectedPatient;
public Patient SelectedPatient {get; set;}
public MainWindowViewModel()
{
LoadingPatients();
//instantiƫren DialogService als singleton
dialogService = new DialogService();
}
private void LoadingPatients()
{
//instantiƫren dataservice
PatientDataService patientDS =
new PatientDataService();
Patienten = new ObservableCollection<Patient>(patientDS.GetPatienten());
}
}
Note that I didn't include all of the code so my datacontext is set with a ViewModelLocator which you cannot see here.
Is there any way to save the image as a resource or do I have to convert all the images in the /bin/debug/assets/images folder to a resource at startup? If so how do I do that?
Apologies for my English, I'm not a native speaker
Thanks for those who had the courage to read all the way to this line and thanks for those who can and will help me!
You can load the Image as ImageSource from your file and bind it to an Image in your view.
public class MyViewModel
{
public void LoadImage()
{
ImageSource = new BitmapImage(new Uri("assets/images/yourImage.jpg", UriKind.Relative));
}
public ImageSource ImageSource { get; set; }
}
In the view:
<Image Source="{Binding Path=ImageSource}"></Image>
As answer to the comment, this works also inside a listbox.
The View:
<ListBox ItemsSource="{Binding Path=MyImages}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Path=ImageSource}"/>
<TextBlock Text="{Binding Path=Name}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The ViewModel:
public class MainWindowViewModel
{
public void LoadImages()
{
var d = new DirectoryInfo("assets/images");
var images = d.GetFiles();
MyImages = images.Select(x => new MyImageModel(x.Name, new BitmapImage(new Uri(x.FullName))));
}
public IEnumerable<MyImageModel> MyImages { get; set; }
}
The MyImageModel
public class MyImageModel
{
public MyImageModel(string name, ImageSource imageSource)
{
Name = name;
ImageSource = imageSource;
}
public string Name { get; set; }
public ImageSource ImageSource { get; set; }
}

how to retrieve multiple images from web service in windows phone 7Thi

I am building an application in windows phone 7 where i need to retrieve multiple images from the web service in a single image view and the images should changes when the user swipes it. I tried it in the following way:
My xaml:
<Image Source="{Binding ImageBind }" HorizontalAlignment="Stretch"
VerticalAlignment="Stretch" Margin="79,61,72,503" Height="187" />
This is my image view where i want to display the images.
The cs code:
public class Rest
{
public string restaurant_image { get; set; }
public BitmapImage ImageBind { get; set; }
}
public const string RestXml = "Rest.xml";
public Restaura()
{
InitializeComponent();
LoadData();
}
private void LoadData()
{
bool isSuccess;
//try to load data from iso store
var doc = ReadXml(out isSuccess);
if (isSuccess) PopulateList(doc);
//if failed (data doesn't exists in iso store), download data from web service
else
{
RahmService.RahmSoapClient client = new RahmService.RahmSoapClient();
client.getRestaurantLocationAllCompleted += new EventHandler<RahmService.getRestaurantLocationAllCompletedEventArgs>(client_getRestaurantLocationAllCompleted);
client.getRestaurantLocationAllAsync();
}
}
void client_getRestaurantLocationAllCompleted(object sender, RahmService.getRestaurantLocationAllCompletedEventArgs e)
{
var doc = XDocument.Parse(e.Result);
PopulateList(doc);
WriteXml(doc);
}
Here i am not getting any result. Please help me with code
Your xaml should be this.
<ListBox Name="ListBoxProduct" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Image Source="{Binding ImageBind }" HorizontalAlignment="Stretch"
VerticalAlignment="Stretch" Height="187" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
In code behind
private void PopulateList(XDocument doc)
{
List<Rest> restList = new List<Rest>();
foreach (var location in doc.Descendants("UserDetails"))
{
Rest data = new Rest();
data.restaurant_image = location.Element("restaurant_image").Value;
data.ImageBind = new BitmapImage(new Uri(#" http://........"
+ data.restaurant_image, UriKind.Absolute));
restList.Add(data);
}
ListBoxProduct.ItemsSource= restList;
}
Try this.

how to display an image from web service

I am building my first app in windows phone 7. I need to show data from web service along with an image. I am able to show the data but not able to show the image.
My xaml code is:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox Name="listBox1">
<ListBox.ItemTemplate>
<DataTemplate>
<Button>
<Button.Content>
<ScrollViewer HorizontalScrollBarVisibility="Auto" Height="80" Width="400">
<!--<ScrollViewer Height="80">-->
<StackPanel Orientation="Horizontal" Margin="0,0,0,0">
<StackPanel Orientation="Vertical" Height="80">
<TextBlock Text="{Binding Path=News_Title}" TextWrapping="Wrap" ></TextBlock>
<TextBlock Text="{Binding Path=News_Description}" TextWrapping="Wrap"></TextBlock>
<TextBlock Text="{Binding Path=Date_Start}" TextWrapping="Wrap"></TextBlock>
<Image Source="{Binding Path=Image_Path}" />
</StackPanel>
</StackPanel>
</ScrollViewer>
</Button.Content>
</Button>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
The .cs code is:
public class Newss
{
public string News_Title { get; set; }
public string News_Description { get; set; }
public string Date_Start { get; set; }
}
public News()
{
InitializeComponent();
KejriwalService.aapSoapClient client = new KejriwalService.aapSoapClient();
client.getarvindNewsCompleted += new EventHandler<KejriwalService.getarvindNewsCompletedEventArgs>(client_getarvindNewsCompleted);
client.getarvindNewsAsync();
}
void client_getarvindNewsCompleted(object sender, KejriwalService.getarvindNewsCompletedEventArgs e)
{
string result = e.Result.ToString();
List<Newss> listData = new List<Newss>();
XDocument doc = XDocument.Parse(result);
foreach (var location in doc.Descendants("UserDetails"))
{
Newss data = new Newss();
data.News_Title = location.Element("News_Title").Value;
data.Date_Start = location.Element("Date_Start").Value;
listData.Add(data);
}
listBox1.ItemsSource = listData;
}
}
Xml String:
<NewDataSet>
<UserDetails>
<id>11</id>
<News_Title>Disciplinary Action against Vinod Binny</News_Title>
<News_Description>The Aam Aadmi Party formed a disciplinary committee, on 19-Jan-2013, headed by Pankaj Gupta to look into the matter of Vinod Kumar Binny. The other members of the committee included Ashish Talwar, Illyas Azmi, Yogendra Yadav and Gopal Rai.
This disciplinary committee has decided to expel Vinod Kumar Binny and terminate his primary membership from the party, for publicly making false statements against the party and its leadership, thereby bringing disrepute to the party. A letter to the same end has been issued to Vinod Kumar Binny.</News_Description>
<Date_Start>2014-01-29</Date_Start>
<image_path>news.png</image_path>
Can anyone help me in displaying the images for each field.
The image path is an http url
http://political-leader.vzons.com/ArvindKejriwal/images/uploaded/news.png
If i guess right your Image_Path is a http url . so you need to BitmapImage to bind as a ImageSource. may this will help you.
public class Newss
{
public string News_Title { get; set; }
public string News_Description { get; set; }
public string Date_Start { get; set; }
**//Edits**
public string image_path {get;set}
public BitmapImage ImageBind{get;set;}
}
foreach (var location in doc.Descendants("UserDetails"))
{
Newss data = new Newss();
data.News_Title = location.Element("News_Title").Value;
data.Date_Start = location.Element("Date_Start").Value;
**//Edits**
data.image_path = location.Element("Image_Path").Value;
data.ImageBind = new BitmapImage(new Uri( #"http://political-leader.vzons.com/ArvindKejriwal/images/uploaded/"+data.image_path, UriKind.Absolute)
listData.Add(data);
}
**Your xaml changes**
<Image Source="{Binding ImageBind }" />

How to determine the clicked item in a gridview

I used this XAML code to create a gridview and add items to it:
<Grid x:Name="MainStack" HorizontalAlignment="Left" Height="628" Grid.Row="1" VerticalAlignment="Top" Width="1366">
<GridView
x:Name="itemGridView"
AutomationProperties.AutomationId="ItemsGridView"
AutomationProperties.Name="Items"
TabIndex="1"
Grid.RowSpan="2"
Padding="130,42,116,46"
ItemTemplate="{StaticResource Standard250x250ItemTemplate}"
SelectionMode="None"
IsSwipeEnabled="false"
IsItemClickEnabled="True"
Background="#FFFB0404" Margin="0,0,0,0" RenderTransformOrigin="0.489,0.503" ItemClick="MainPage_Click">
<x:String>Item 1</x:String>
<x:String>Item 2</x:String>
<x:String>Item 3</x:String>
<x:String>Item 4</x:String>
<x:String>Item 5</x:String>
<x:String>Item 6</x:String>
<x:String>Item 7</x:String>
<x:String>Item 8</x:String>
</GridView>
</Grid>
Then I tried using this C# code
private void MainPage_Click(object sender, ItemClickEventArgs e)
{
string output = e.ClickedItem.ToString();
int ClickValue = Convert.ToInt32(output);
if (ClickValue == 0)
{
this.Frame.Navigate(typeof(ItemsPageRSS));
}
}
to make the app navigate to a page when the 1st item is clicked but it gave an error.
Please if anyone can tell me how to isolate each iem and add a seperate click event for each and how to customize the gridview items by adding titles, subtitles and images to the items.
Thank you in advance.
Here I am giving you simple example if you can't understand MSDN sample. Just create new project and paste the whole code.
XAML
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<GridView
x:Name="itemGridView"
ItemTemplate="{StaticResource Standard250x250ItemTemplate}"
SelectionMode="None"
IsItemClickEnabled="True"
Background="#FFFB0404"
ItemClick="MainPage_Click"/>
</Grid>
C#
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var gvData = new ObservableCollection<MyData>();
for (int i = 0; i < 8; i++)
{
gvData.Add(new MyData
{
ID = i,
Image = new BitmapImage(new Uri("ms-appx:///Assets/Logo.png")), //You can add any image
Title = "Title " + i,
Subtitle = "Subtitle " + i
});
}
itemGridView.ItemsSource = gvData;
}
private void MainPage_Click(object sender, ItemClickEventArgs e)
{
MyData output = e.ClickedItem as MyData;
int ClickValue = output.ID;
if (ClickValue == 0)
{
this.Frame.Navigate(typeof(ItemsPageRSS));
//TODO : Do whatever you want
}
//.....
//TODO : Do operations for other items as well.
}
You may create MyData class outside the scope of MainPage (XAML Page) class.
public class MyData
{
public int ID { get; set; }
public ImageSource Image { get; set; }
public string Title { get; set; }
public string Subtitle { get; set; }
}

Data Binding Bing Maps pushpin

I'm having a bit of trouble extracting some information I need when I pass a data binding in Xaml for a windows 8 app.
I have a default template designed in the app.xaml here:
<DataTemplate x:Key="PinTemplate">
<bm:Pushpin Name="{Binding img}" IsTapEnabled="True" >
<bm:MapLayer.Position>
<bm:Location Latitude="{Binding Latitude}" Longitude="{Binding Longitude}" />
</bm:MapLayer.Position>
</bm:Pushpin>
</DataTemplate>
I want to access the individual "img" strings from the binding above. On my map I have an itemcontrol embedded like so:
<Maps:Map Name="london" HorizontalAlignment="Left" Height="546" Margin="78,34,0,0" Grid.Row="1" VerticalAlignment="Top" Width="806" Credentials="{StaticResource BingCredentials}" RenderTransformOrigin="0.439,0.282">
<Maps:Pushpin Name="myPin" Height="100" Width="100"/>
<Maps:MapItemsControl ItemTemplate="{StaticResource PinTemplate}" ItemsSource="{Binding PushpinCollection}" Height="100" Width="100" Tapped="pushPin_Tapped"/>
<Popup VerticalOffset="200" HorizontalOffset="300" x:Name="Image" IsLightDismissEnabled="True" Height="2000" Width="2000" >
<Image Name="myImage" Height="300" Width="300" Source="Assets/Logo.png"/>
</Popup>
</Maps:Map>
And the c# behind it is:
public class PushpinModel
{
public double Longitude { get; set; }
public double Latitude { get; set; }
public string img { get; set; }
}
public ObservableCollection<PushpinModel> PushpinCollection { get; set; }
PushpinCollection = new ObservableCollection<PushpinModel>();
PushpinCollection.Add(new PushpinModel() { Latitude = templat[0], Longitude = templng[0], img = names[0] });
PushpinCollection.Add(new PushpinModel() { Latitude = templat[1], Longitude = templng[1], img = names[1] });
DataContext = this;
As it stands now I have an action control "Tapped" on the MapsItemcontrol which works properly, it creates a popup and displays a picture. However I would like to pass the information in img to the action controller so that I can specify which image to display in specific pushpins. I tried to do it like below but I think it the data context it returns is for the itemscontrol as a whole, how do I access the properties within the data template for each individual instance of pushpincollection? Thanks
private void pushPin_Tapped(object sender, TappedRoutedEventArgs e)
{
if (!Image.IsOpen) { Image.IsOpen = true; }
var pushpinData = (sender as Pushpin).DataContext as PushpinModel;
String file = pushpinData.ToString();
// use image in popup here
}
Try
var pushpinData = (sender as FrameworkElement).DataContext as PushpinModel;
That's how I usually do it, cause you don't always know what the sender type is but to me it seems it is the Pushpin..

Categories

Resources