Loading image from projects files - image

I'm trying to get png image which is my Resource folder. I tested solution that was written here :Add images to ListBox (c#, windows phone 7). For start I wanted to get the same image for every item in my ListBox. But I can't achive that. The picture doesn't show.
It's how my list in xaml look like:
<ListBox x:Name="ProductList">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}"/>
<Image Source="{Binding ImagePath}" Stretch="None"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
This is how I populate Items:
List<ImageData1> productsList = new List<ImageData1>();
foreach (ProductItem item in ProductsTable)
{
if (item.Category == chosenCategory.TrId)
{
ImageData1 img = new ImageData1();
img.Name = item.Name;
img.ImagePath = new Uri("Resources/img.png", UriKind.RelativeOrAbsolute);
productsList.Add(img);
}
}
ProductList.ItemsSource = productsList;
Here is my class to hold image data:
public class ImageData1
{
public Uri ImagePath
{
get;
set;
}
public string Name
{
get;
set;
}
}

Try putting / before your image path. Like /Resources/img.png. And try to change UriKind.RelativeOrAbsolute to UriKind.Relative. And make sure your images are added as Content (Build Action property of image). That way it works for me.

Probably, You can also use the following assembled code to read the image from the current application.
StreamResourceInfo info =Application.GetResourceStream(new Uri("Resources/img.png", UriKind.RelativeOrAbsolute));
var bitmap = new BitmapImage();
bitmap.SetSource(info.Stream);
img.Soure = bitmap;

Related

Collectionview items font size

I am trying to make funcionality, to make larger text across whole application for user when he clicks a 'increase font size' button. Using MVVM, I have done it like this:
Increase font size button click
increase value of double field 'fontSize' which is binded to almost every text in layout
Update UI with new value after button click
However I don't know how to achieve this in Collectionview where I have got Binding in .xaml file, with some particular List (item is model class). The collectionview DataTemplate contains labels where I want to increase font size. Is there a way to do this without adding 'fontSize' field in my model class. If not how to update UI with 'new' List with increased font sizes.
I appreciate any help, tips and discussions.
Thank you.
You can create bindableproperty(fontsize) in your viewmodel and use Relative Binding so the label in Collectionview can change it's fontsize,code like:
ViewMode:
public class ColViewModel:BindableObject
{
public ObservableCollection<Student> students { set; get; }
public static readonly BindableProperty FontSizeProperty =
BindableProperty.Create("fontsize", typeof(int), typeof(ColViewModel), null);
public int fontsize
{
get { return (int)GetValue(FontSizeProperty); }
set { SetValue(FontSizeProperty, value); }
}
public ICommand IncreaseCommand { private set; get; }
public ColViewModel()
{students = new ObservableCollection<Student>();
getStudents();
fontsize = 24;
IncreaseCommand = new Command(() => {
fontsize++;
});
}
View:
<StackLayout>
<Label Text="This is a Title" FontSize="{Binding fontsize}"/>
<CollectionView ItemsSource="{Binding students}">
<CollectionView.ItemTemplate>
<DataTemplate>
<Label Text="{Binding Name}" FontSize="{Binding Source={RelativeSource AncestorType={x:Type local:ColViewModel}}, Path=fontsize}"/>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
<Button Text="Click to increase fontsize" Command="{Binding IncreaseCommand}"/>
</StackLayout>
Edit:
xmlns:local="clr-namespace:MyForms2.ViewModels"

ListBox with multiple captured images windows phone

Does anyone know how to make a listbox with multiple images. I want to be able to capture an image and then display on the screen, then capture another and display after the first one and so on. It is basically images gallery page that I want to create. I would like to store them somewhere on the phone, so they can be retrieved when the application runs again.
So it should be something like in the picture: http://blog.xamarin.com/wp-content/uploads/2012/02/wp2.png
Thank you in advance, I have been doing researches about it but can't find anything.
Well, that is fairly easy. You use a ListBox set the ItemsPanel to a WrapPanel, and either bind ItemsSource to a ObservableCollection (or List/Array, but ObservableCollection is better suited for Bindings).
There are multible ways to do it
Lets take the easiest approach. In xaml you define your ListBox:
<ListBox x:Name="listbox">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<toolkit:WrapPanel />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Margin="5"
Background="{StaticResource PhoneChromeBrush}"
Height="180"
Width="180">
<Image Source="{Binding}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
In your code behind, you can load the images with something like this:
ObservableCollection<BitmapImage> images = new ObservableCollection<BitmapImage>();
List<String> bitmapuris = ....
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
foreach(var bitmapuri in bitmapuris)
{
System.Windows.Media.Imaging.BitmapImage bitmap = new System.Windows.Media.Imaging.BitmapImage();
if (isoStore.FileExists(bitmapuri))
{
using (IsolatedStorageFileStream stream = isoStore.OpenFile(bitmapuri, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
bitmap.CreateOptions = System.Windows.Media.Imaging.BitmapCreateOptions.BackgroundCreation;
bitmap.SetSource(stream);
}
}
images.Add(bitmap);
}
}
listbox.ItemsSource = images;
With bitmapuris being a List with all of your saved images urls.
Thats basicly what I'm using in some of my apps (though I use ViewModels and Bindings and don't set ItemsSource manually)
Hope this helps
edit:
On how to capture and save images you can read this article:
http://www.c-sharpcorner.com/UploadFile/mahakgupta/capture-save-and-edit-image-in-windows-phone-7/
I would save the Images in a specific folder i.e. "/Images/". That way you can load all images you previously captured on you app start with the code I posted above with List<String> bitmapuris set with this method:
List<String> getFiles(String folderpath)
{
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
return storage.GetFileNames(folderpath).ToList();
}
like this List<String> bitmapuris = getFiles("/Images/*");
and when you captured an image you can simple add your image to your ListBox this way:
System.Windows.Media.Imaging.BitmapImage bitmap = new System.Windows.Media.Imaging.BitmapImage();
bitmap.CreateOptions = System.Windows.Media.Imaging.BitmapCreateOptions.BackgroundCreation;
bitmap.SetSource(myimagestream);
images.Add(bitmap);
providing images is the ObservableCollection<BitmapImage> you set as an ItemsSource to your ListBox.
This is now almost your fully working app, when compined with the link from above.

Windows Phone Adding to List issue

(Windows Phone 7 SDK)
Hi,
I have a ListBox named CTransactionList, and adding some items to this listbox by using data bindings. And Here I have a class to evaulate data bindings.(I think my listbox's XAML code is not needed here as my issue comes out due to some coding problems)
public class CTransaction
{
public String Date1 { get; set; }
public String Amount1 { get; set; }
public String Type1 { get; set; }
public CTransaction(String date1, String amount1, String type1)
{
this.Date1 = date1;
this.Amount1 = amount1;
switch (type1)
{
case "FR":
this.Type1 = "Images/a.png";
break;
case "TA":
this.Type1 = "Images/b.png";
break;
case "DA":
this.Type1 = "Images/c.png";
break;
}
}
}
Here I have a function, when a move completes, this function runs;(this function is supposed to add new items when function runs)
List<CTransaction> ctransactionList = new List<CTransaction>();//Define my list
public void movecompleted()
{
String DefaultDate = "";
String DefaultAmount = "";
String RandomType = "";
DefaultDate = nameend.Text;
DefaultAmount = diffend.Text;
RandomType = "FR";
ctransactionList.Add(new CTransaction(DefaultDate, DefaultAmount, RandomType));
CTransactionList.ItemsSource = ctransactionList;
}
For the first time when move completes, it adds the required elements to my list. But for next times, it does not add to my list. The old one keeps its existence. I tried also this format by getting list definition into my function like:
public void movecompleted()
{
List<CTransaction> ctransactionList = new List<CTransaction>(); //List definition in function
String DefaultDate = "";
//...Same
}
And this time, it replaces my current item with new one. Do not append at the end of list. (Both ways, I have one item in my list, not more) How can I do everytime append to list? Where am I wrong?
Here is my Debugging report. Both ctransactionList object and CTransactionList ListBox have the needed items according to my observations in debug watcher. Only problem, CTransactionList cant refresh itself properly even if it has the resources retrieved from ctransactionList object.
Here is my XAML code for my relevant listbox.(IF NEEDED)
<Grid>
<ListBox Name="CTransactionList" Margin="0,0,0,0" >
<ListBox.ItemTemplate >
<DataTemplate>
<Button Width="400" Height="120" >
<Button.Content >
<StackPanel Orientation="Horizontal" Height="80" Width="400">
<Image Source="{Binding Type1}" Width="80" Height="80"/>
<StackPanel Orientation="Vertical" Height="80">
<StackPanel Orientation="Horizontal" Height="40">
<TextBlock Width="100" FontSize="22" Text="Name:" Height="40"/>
<TextBlock Width="200" FontSize="22" Text="{Binding Date1}" Height="40"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Height="40">
<TextBlock Width="100" FontSize="22" Text="Difficulty:" Height="40"/>
<TextBlock Width="200" FontSize="22" Text="{Binding Amount1}" Height="40"/>
</StackPanel>
</StackPanel>
</StackPanel>
</Button.Content>
</Button>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
Thanks in advance.
As you rightly mentioned, it's not related to your XAML. Problem is in your code.
First simple fix may to clear the ItemsSource before setting the new source, like this
CTransactionList.ItemsSource = null;
CTransactionList.ItemsSource = ctransactionList;
This way, you are clearing the existing the databinding and enforcing the new list into the ListBox.
The other and suggestible fix is,
"Change your List to ObservableCollection. Because, ObservableCollection extends the INotifyPropertyChanged and hence has the ability to auto update the ListBox"
List<CTransaction> ctransactionList = new List<CTransaction>();//Change this to below
ObservableCollection<CTransaction> ctransactionList = new ObservableCollection<CTransaction>();//Define my collection
But a breakpoint before
CTransactionList.ItemsSource = ctransactionList;
And run the function twice. Do you have two items in ctransactionList now?
I suspect the binding fails and ctransactionList are in fact increasing

pass data from viewmodel to code behind windows phone

I was trying to use the MVVM pattern on my first (very simple) WP7 app but I got seriously stuck and now I am just trying to get it working without caring about MVVM.
I have a MainViewModel for my MainPage, which works fine. I have a button that passes some data and navigates to a "details page." I had setup a navigation service to navigate to the details page and pass parameters, which works fine. I just couldn't get the databinding to the view working. Since it is a simple app, I decided I would pass the data from the DetailsPageVieModel.cs to the DetailsPage.xaml.cs code behind and do the work there. Here is what that veiw model portion looks like.
public override void Initialize(IDictionary<string, string> parameters)
{
DetailsPage dp = new DetailsPage();
//DetailsPage dp = Application.Current.RootVisual as DetailsPage;
base.Initialize(parameters);
parameters.TryGetValue("url", out vidUrl);
dp.LoadVideoData(vidUrl);
}
In my DetailsPage.xaml.cs I have the following:
public void LoadVideoData(string url)
{
HtmlWeb doc = new HtmlWeb();
doc.LoadAsync("http://mydomain.com/video.php?url=" + url);
doc.LoadCompleted += doc_LoadCompleted;
}
private void doc_LoadCompleted(object sender, HtmlDocumentLoadCompleted e)
{
this.vidTitle.Text = e.Document.GetElementbyId("title").InnerText;
vidId = e.Document.GetElementbyId("youtubeId").InnerText;
this.vidUrl.Source = new Uri("http://mydomain.com/video.php?url=" + vidUrl, UriKind.Absolute);
BitmapImage bi = new BitmapImage();
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("temp.jpg", FileMode.Open, FileAccess.Read))
{
bi.SetSource(fileStream);
this.vidImg.Height = bi.PixelHeight;
this.vidImg.Width = bi.PixelWidth;
}
}
this.vidImg.Source = bi;
}
And here is the relevant DetailsPage.xaml code
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<StackPanel>
<TextBlock x:Name="vidTitle" Canvas.ZIndex="99" />
<TextBlock Canvas.ZIndex="99" Text="Tap on the image to view the video." FontSize="14" Margin="0"/>
<Button Margin="0 -50" Padding="0" BorderThickness="0">
<Image x:Name="vidImg" Height="225" />
</Button>
<StackPanel Canvas.ZIndex="99" Height="516">
<phone:WebBrowser x:Name="vidUrl" IsScriptEnabled="True" Height="516" Margin="0"/>
</StackPanel>
</StackPanel>
</Grid>
I am guessing the problem lies with the following
DetailsPage dp = new DetailsPage();
//DetailsPage dp = Application.Current.RootVisual as DetailsPage;
Neither of these lines of code works. The first line executes properly but the page doesn't get updated with the proper data. And the second line gives me a runtime error message when it gets to the dp.LoadVideoData(vidUrl); line.
This is my first Windows Phone app and I would appreciate any help anyone can provide.
Kamal
After digging around some more, I found the following solution.
DetailsPage currentPage = (App.Current as App).RootFrame.Content as DetailsPage;
I put this code in DetailsPageViewModel.cs. But for other newbies like me, there is nothing special about the name of the file. It could have very well been Monkey.cs. The above code just gives you access to the code behind of the current page being displayed.

binding property of one field to another in wp7

<TextBlock Name="currency" TextWrapping="Wrap" VerticalAlignment="Center"/>
<TextBlock Margin="5,0" Text="{Binding Text, ElementName=currency" TextWrapping="Wrap" VerticalAlignment="Center" FontSize="22" />
I am using the above code for binding property of one field to another in my WP7 application.
i want to do the similar task from back-end. any suggestions??
Bindings are working in a specified data context. You can set the data context of your layout root to the page instance, then you can bind to any of your properties. (DataContext is inherited through the child FrameworkElements.) If you want your binding to update its value whenever you change your property from code, you need to implement INotifyPropertyChanged interface or use Dependency properties.
<Grid x:Name="LayoutRoot">
<TextBox Text="{Binding Test, Mode=TwoWay}" />
</Grid>
public class MainPage : PhoneApplicationPage, INotifyPropertyChanged
{
private string test;
public string Test
{
get { return this.test; }
set
{
this.test = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("Test"));
}
}
public MainPage()
{
InitializeComponents();
LayoutRoot.DataContext = this;
}
public event PropertyChangedEventHandler PropertyChanged;
}
This is a stupid example since you can access your TextBox any time from MainPage, this has much more sense if you are displaying model objects with DataTemplates.
(I typed this on phone, hope it compiles..)
i got my solution as: var b = new Binding{ElementName = "currency", Path = new PropertyPath("Text")}; Textblock txt = new TextBlock(); txt.SetBinding(TextBlock.TextProperty, b);

Resources