XamlParseException when binding to listbox - c#

In my app I am allowing users to save photos from camera and photo library to isolated storage. I then get the name of each file and read the photo and add to my list. Once the list is built, I bind it to the list box.
I can get about 5 displayed without a problem. After I scroll I get the exception:
System.Windows.Markup.XamlParseException occurred
Message= [Line: 0 Position: 0]
--- Inner Exception ---
KeyNotFoundException
This is my XAML:
<ListBox x:Name="userPhotosListBox">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel x:Name="DataTemplateStackPanel" Orientation="Horizontal">
<ContentControl Content="{Binding Image}" Width="400" />
<Image Name="{Binding FileName}" Source="/Images/appbar.delete.rest.png" Width="48" Height="48"
MouseLeftButtonUp="Image_MouseLeftButtonUp" VerticalAlignment="Center" HorizontalAlignment="Center" MaxWidth="48" MaxHeight="48" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
This is the code:
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
var userFiles = store.GetFileNames();
foreach (var userFile in userFiles)
{
if (userFile.Contains(PhotoInIsolatedStoragePrefix))
{
var currentBitmap = ReadBitmapImageFromIso(userFile);
var userPhotoImage = new Image { Source = currentBitmap };
var userImg = new Img(userPhotoImage, userFile);
userPhotosListBox.Items.Add(userImg);
}
}
}
public class Img
{
public Img(Image img, string fileName)
{
this.Image = img;
this.FileName = fileName;
}
public Image Image { get; set; }
public string FileName { get; set; }
}
Very new to WP7 development and confused as to why my code partially works.

I think you made a mistake in: Name="{Binding FileName}"
Name must start with a letter or the underscore character (_), and must contain only letters, digits, or underscores: look here
I think some of your file names are not math with these principles
Use another property like Tag instead.

Check out this post: XAMLParseException driving me CRAZY!
The bottom line is that often a XmlParseException is actually a TargetInvocationException which can be determined in the InnerException. That could be an anchor for further investigation.
Use a:
try
{
}
catch(Exception ex)
{
}
construct and set a breakpoint at the catch. Then inspect the ex variable in greater detail to see if it contains a InnerException that may give you more insight.

Related

Exception in ZXingBarcodeImageView when removing from ObservableCollection

I'm using an ObservableCollection<BarcodeInfo> as ItemsSource of a ListView to generate ViewCells. A Cell contains 2 Labels and a ZXingBarcodeImageView with bindings to my BarcodeInfo-class, everything works as expected.
Now I've to remove several cells from the ListView, but as soon as I try to do so, I get the following Exception from the ZXingBarcodeImageView
System.ArgumentException: Found empty contents
Here's my XAML
<ListView RowHeight="50">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="3*" />
</Grid.ColumnDefinitions>
<zxing:ZXingBarcodeImageView
BarcodeFormat="{Binding Format}"
BarcodeOptions="{Binding Options}"
BarcodeValue="{Binding Text}"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand"
Margin="5"
Grid.Column="0"/>
<StackLayout Grid.Row="0" Grid.Column="1"
Spacing="0" VerticalOptions="CenterAndExpand">
<Label Text="{Binding Text}"
LineBreakMode="TailTruncation"
VerticalOptions="End"/>
<Label Text="{Binding Format}"
VerticalOptions="End"
LineBreakMode="TailTruncation"/>
</StackLayout>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
And the Class for ObservableCollection<BarcodeInfo> _barcodeCollection; in the of the ListView
public class BarcodeInfo
{
public string Text
{ get; set; }
public string Detail
{ get; set; }
public BarcodeFormat Format
{ get; set; }
public EncodingOptions Options
{ get; set; }
}
The Exceptions happens as soon as I try
_barcodeCollection.RemoveAt(i);
I've implemented the INotifyPropertyChanged and tried to set all properties to null which works without exception, but the ZXingBarcodeImageView is not clearing the barcode-image and the Exception is still thrown if I try to remove the Item from the Collection. I'm at a point where I've no more ideas.
I hope anybody can help me.
Update
Because the i seems to be confusing here's the loop I'm using it
for (int i = 0; i < _barcodeCollection.Count; i++)
{
var response =
await _serverUrl.PostUrlEncodedAsync(
new { barcode = _barcodeCollection[i].Text })
.ReceiveString();
if (string.Equals(response, "ok", StringComparison.OrdinalIgnoreCase))
{
percentage += progressSteps;
_barcodeCollection.RemoveAt(i); //EXCEPTION!!!
i--; // index must be checked twice else one element will be skipped
await UploadProgress.ProgressTo(percentage, 250, Easing.Linear);
}
}
Not a straightforward solution, but the easiest workaround I've found was to provide FallbackValue when binding BarcodeValue
<forms:ZXingBarcodeImageView BarcodeFormat="{Binding Format}"
BarcodeValue="{Binding Content, FallbackValue='1'}" />
I have managed to identify the cause of the problem, it is a side effect of the way that the ListView is refreshed when the elements are removed and the ListViewCachingStrategy is set to RetainElement (the default).
The custom renderer OnElementPropertyChanged is called when the items are removed from the collection, and the regenerate() method in the ZXing custom renderer crashes.
This can be solved by setting the ListViewCachingStrategy to RecycleElement, this will work with Android, however there is still a problem with iOS 10, which does not correctly support a listview with ListViewCachingStrategy set to RecycleElement, iOS 10 currentlly works only with ListViewCachingStrategy set to RetainElement, this can be accommodated if you create a custom control in your portable code eg:
public class MyZXingBarcodeImageView : ZXingBarcodeImageView
{
//THERE IS NO CODE REQUIRED HERE
}
And then create your own custom renderer based on the ZXing source, but replace the void regenerate() method with the following:
void regenerate()
{
if(formsView != null && !string.IsNullOrWhiteSpace(formsView.BarcodeValue) )
{
var writer = new ZXing.Mobile.BarcodeWriter();
if(formsView != null && formsView.BarcodeOptions != null)
writer.Options = formsView.BarcodeOptions;
if(formsView != null && formsView.BarcodeFormat != null)
writer.Format = formsView.BarcodeFormat;
var value = formsView != null ? formsView.BarcodeValue : string.Empty;
Device.BeginInvokeOnMainThread(() =>
{
var image = writer.Write(value);
imageView.Image = image;
});
}
}
The change is in the very first If statement, changing from testing for null string to string.IsNullOrWhiteSpace
You do NOT have to create a custom renderer for Android if you use ListViewCachingStrategy set to RecycleElement, the base renderer for ZXingBarcodeImageView will be used without error.

Windows Phone 8.1 with Bing maps returns Access violation

I am trying to bind a collections of points to the Bing map control and everything works great for the first time (when I am opening the view with this map for the first time) but every another attempt end up with this pure message in the output window:
The program 'xxx' has exited with code -1073741819 (0xc0000005) 'Access violation'.
There is no exceptions, nothing only this message. What I have tried so far is this article from MSDN but without success. I have also tried to run the code on the UI thread but it didn't help.
In the ViewModel I am doing this:
Issues.Completed += () =>
{
Locations = new ObservableCollection<MapItemViewModel>();
foreach (var issueLto in Issues.Result)
{
Locations.Add(new MapItemViewModel
{
Name = issueLto.Title,
Location = new MapPointViewModel
{
Longitude = issueLto.Longitude,
Latitude = issueLto.Latitude
}
});
}
MapCenter = Issues.Result.Select(c => new MapCenterViewModel
{
Location = new MapPointViewModel
{
Latitude = c.Latitude,
Longitude = c.Longitude
}
}).FirstOrDefault();
};
And the XAML:
<maps:MapControl
MapServiceToken="{StaticResource BingServiceToken}"
VerticalAlignment="Stretch"
HorizontalAlignment="Stretch"
Center="{Binding MapCenter.Location, Converter={StaticResource MapCoordinatesConverter}}">
<maps:MapItemsControl ItemsSource="{Binding Locations}">
<maps:MapItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel maps:MapControl.Location="{Binding Location, Converter={StaticResource MapCoordinatesConverter}}">
<TextBlock Text="{Binding Name}" Foreground="Black"/>
<Image Source="../../Assets/mappin.png" Height="25"/>
</StackPanel>
</DataTemplate>
</maps:MapItemsControl.ItemTemplate>
</maps:MapItemsControl>
</maps:MapControl>
It's maybe because you can't bind the center property of the Map Control, there's a workaround using Behavior SDK, please read this article:
http://dreamteam-mobile.com/blog/2012/10/better-bing-maps-sdk-for-metro-apps-winrt-windows8-en/
in MSDN, this is helpful:
https://social.msdn.microsoft.com/Forums/en-US/436fc737-19c8-4832-a1c4-368f88063616/anyway-to-make-a-binding?forum=bingmapswindows8

Display images from Assets with JSON - Windows Phone 8

I am making a WP8 application with a lot of local content in my Assets folder. So I am using a JSON file stored in the a JSON folder.
I have been able to parse the JSON to C# very easily and now I am trying to display the data in a list. I had no problem with displaying the title but I am unable to display an image, even with the filename I am got.
My images are stored in "Assets/Content/mediaXXX.jpg";
ListViewModel :
public class ListViewModel
{
public string Title { get; set; }
public string Subtitle { get; set; }
public BitmapImage ListImage { get; set; }
}
XAML
<ListBox Margin="0,1,0,0"
Height="730"
x:Name="MainList">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Height="120"
Width="480">
<StackPanel Orientation="Horizontal">
<Image HorizontalAlignment="Left"
Source="{Binding ListImage}"
Margin="12"
Stretch="UniformToFill"
Width="130"/>
<Grid>
<TextBlock x:Name="ListItemTitle"
Text="{Binding Title}"/>
<TextBlock x:Name="ListItemSubTitle"
Text="{Binding Subtitle}"/>
</Grid>
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And my C# page
BitmapImage image = new BitmapImage(new Uri(#"Assets/Content/" + photo.filename + ".jpg", UriKind.Relative);
l.ListImage = image;
Any idea?
Code should work. Only problems that might occur is your ListBox databinding is incorrectly defined.
I don't see any .ItemsSource = or ItemsSource={Binding some_collection}
Another thing is make sure that photo.filename is returning the correct file.
Set a string debug_string = "Assets/Content/" + photo.filename + ".jpg";
Make sure everything is correct.
Last thing is to make sure the files are actually in the Assets Folder inside the project and its
BuildAction is set to Content
like so

XAML, Image control, local storage image

The first is the first, I'm very newbie on .NET, I was developed un Visual Basic 6, but now I'm trying to make an application to Windows Phone 8.0.
At this time I'm trapped with a (maybe simple) problem.
I have a xaml page with control, and it is part of LongListSelector thats implements an Observable Collection of "Prenda" class.
...
var prendasData = from r in db.Prendas select r;
PrendasItems = new ObservableCollection<Prenda>(prendasData);
llsPrendas.ItemsSource = PrendasItems;
...
The XAML portion is the code bellow, please, i know that severals things maybe are wrong, but I'm learning alone, be patient with me :D
<phone:LongListSelector x:Name="llsPrendas" Margin="0,0,-12,0" ItemsSource="{Binding Prendas}" SelectionChanged="llsPrendasSelectionChanged">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel>
<Image Width="100" Height="100" Margin="5,0,0,0" Source="{Binding PrendaImageURI}" ImageFailed="errcargaimg"/>
<StackPanel Orientation="Vertical">
<TextBlock FontWeight="Normal" Text="{Binding Nombre}" Margin="10,0,0,0" />
<TextBlock FontWeight="Normal" Text="{Binding Precio}" Margin="10,0,0,0" />
</StackPanel>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
The problem is the Image Control. It doesn't show anything and if I debug it, the error the message is: "AG_E_NETWORK_ERROR", googled this error and I know that is (in this case) same as "File not found." But I'm sure thats file exists. because I seen it with IsoStoreSpy, at /Shared/Media/ShellContent/WP_XXX.jpg, i think that the root of the Isolated Storage is called isostore:/ and the complete URI must be: isostore:/Shared/Media/ShellContent/WP_XXX.jpg.
This string is saved as string column in the class, and I create a property thats use this string to make an Uri to use to bind the Source property of Image control at design time.
(portion of class declaration)
[Column]
public string Foto
{
get
{
return foto;
}
set
{
if (foto != value)
{
foto = value;
NotifyPropertyChanged("Foto");
}
}
}
public Uri PrendaImageURI
{
get
{
return new Uri(this.Foto, UriKind.Absolute);
}
}
I'm going crazy, because I cannot understand why it's doesn't work. Can somebody help me? (Sorry for my bad english)
You can not read from Isolated storage using URI, You have to read using IsolatedStorageFile class:
private static BitmapImage GetImageFromIsolatedStorage(string imageName)
{
var bimg = new BitmapImage();
using (var iso = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var stream = iso.OpenFile(imageName, FileMode.Open, FileAccess.Read))
{
bimg.SetSource(stream);
}
}
return bimg;
}
You can find more details from below Posts:
How get image from isolated storage
How to load an image from isolated storage into image control on windows phone?
I solved it with Pratik Goyal help (thank you, very much!), making a BitmapImage Property in the class "Prendas", taking The Foto string data. Later I will take more careful with the exception control, but is a good start, I think.
public BitmapImage ImageFoto
{
get
{
return GetImageFromIsolatedStorage(Foto);
}
}
public BitmapImage GetImageFromIsolatedStorage(string imageName)
{
var bimg = new BitmapImage();
using (var iso = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var stream = iso.OpenFile(imageName, FileMode.Open, FileAccess.Read))
{
bimg.SetSource(stream);
}
}
return bimg;
}
Just for the children:
Silverlight notifies this with an AG_E_NETWORK_ERROR / HRESULT=0x80131500. Which of course can't be found anywhere on the web and of course means jack and shit to me and not only to me.
Is the UI being notified of the PrendaImageURI property changing?
Try adding
NotifyPropertyChanged("PrendaImageURI");
when your Foto property is set.

c# link objects wrapped on the listbox in WINDOWS PHONE

I have this block of code as you can see in the screen print correctly loads the data you want and store the list of objects PopularVideos:
item { Title = Hey Porsche, Url = http://www.unnu.com/wp-content/plugins/wordpress-popular-posts/timthumb.php?src=http://www.unnu.com/wp-content/uploads/2013/03/019.jpg&h=65&w=275 } <>f__AnonymousType0<string,string>
item.Title "Hey Porsche" string
item.Url "http://www.unnu.com/wp-content/plugins/wordpress-popular-posts/timthumb.php?src=http://www.unnu.com/wp-content/uploads/2013/03/019.jpg&h=65&w=275" string
Need to load these objects in my list box with binding or has otherwise also can be. But the windows phone does not work with DataSource and DisplayMember.
My XAML:
<ListBox Name="listBoxPopular">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Image Name="imagem" Source="{Binding Path=Url}"/>
<TextBlock Text="{Binding Titulo}" Tap="HyperlinkButton_Tap" FontSize="30" Foreground="#FF159DDE" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</controls:PanoramaItem>
My Class is:
class PopularVideos
{
public PopularVideos() { }
public PopularVideos(string titulo, string url)
{
Titulo = titulo;
BitmapImage Img = new BitmapImage(new Uri(url));
}
public string Titulo { get; set; }
public Uri Url { get; set; }
}
and my codebehind is:
_popVideos = new List<PopularVideos>();
var data = e.Document.DocumentNode.SelectSingleNode("//div[#class='content']")
.Descendants("img")
.Select(img => new
{
Title = img.Attributes["alt"].Value,
Url = img.Attributes["src"].Value,
}).ToList();
foreach (var item in data)
{
PopularVideos pop = new PopularVideos(item.Title, item.Url);
_popVideos.Add(new PopularVideos(item.Title, item.Url));
}
listBoxPopular.ItemsSource = _popVideos;
This code works because they are carrying the images and links in the objects, just can not bring up in my list box.
Have a bindable ObservableCollection<Item> (preferrably in a ViewModel).
Use the ListBox.ItemsSource property to bind to said ObservableCollection<Item>. The standard binding rules apply.
Each of the items in ListBox will be a representation of the items in the core collection that is bound to the control, so bind to its properties the same way you would to anything else.
It's reply to comment:
Ok, please read once again the article that #Den send to you. And please remove DataContext Property from ListBox, add x:Name="myList" to ListBox and in code-behind: myList.DataContext = this; This is not the best solution, but it's easy to understand and firstly you need to understand it :) Best regards.

Categories