How can I bind AlbumArt to my listbox?
My code:
<ListBox Name="albumLb" Margin="0,0,-12,0" ItemsSource="{Binding Items}" SelectionChanged="albumLb_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="0,0,0,17" >
<!--Replace rectangle with image-->
<Image Source="{Binding }"/>
<StackPanel Width="311">
<TextBlock Text="{Binding Name}" FontSize="28" />
<TextBlock Text="{Binding Artist}" Margin="12,-6,12,0" Foreground="#FFE5CDCD"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And in my code I use:
albumLb.ItemsSource = library.Albums;
I know that I can get the AlbumArt by library.Albums[int index].getAlbumArt() but I don't know how to bind it into my listbox.
What type does getAlbumArt() return? If it is simply a path to a file (say in Isolated Storage) then you'll have to write a converter to do the binding. Also, instead of having a function called getAlbumArt(), create a property named AlbumArt instead with a public getter, which will allow binding to it. Then you can bind the image using
<Image Source="{Binding AlbumArt}" />
Next, create a converter (by implementing the IValueConverter interface) that will take the path to a file in Isolated Storage, and load it into a BitmapImage which is then returned to the Image in your ListBox by the converter.
This question has details on how to do this.
On the other hand, if you need to download the image from some website, use WebClient.OpenReadAsync.
WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(OnImageDownloadCompleted);
wc.OpenReadAsync(new Uri("www.mywebsite.com/albumart/album1.jpg", UriKind.Relative));
void OnImageDownloadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null) {
StreamResourceInfo sri = new StreamResourceInfo(e.Result as Stream, null);
BitmapImage imgsrc = new BitmapImage();
imgsrc.SetSource(sri.Stream);
}
}
Related
If I hide an image visibility in CollectionView, multiple image visibility is affecting but image Tapped event fires once.
Simplified CollectionView xaml..
<CollectionView x:Name="favCollectionView"
ItemsSource="{Binding FavoriteCollection}"
RemainingItemsThresholdReachedCommand="{Binding GetNextDatas}"
RemainingItemsThreshold="1"
ItemSizingStrategy="MeasureAllItems"
ItemsLayout="VerticalList"
SelectionMode="Single">
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid VerticalOptions="FillAndExpand">
<Label Grid.Row="0" Text="{Binding TargetText}"/>
<Image Grid.Row="0" Aspect="AspectFill" Source="seeResult.png">
<Image.GestureRecognizers>
<TapGestureRecognizer Tapped="Tapped_TranslatedResult"/>
</Image.GestureRecognizers>
</Image>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
Code behind..
void Tapped_TranslatedResult(System.Object sender, System.EventArgs e)
{
var img = sender as Image;
if (img != null)
{
img.Opacity = 0;
}
}
For example, If I have 50 rows in CollectionView and tapped once top second image item, next ninth image's visibility is changed too and again next ninth one too, so on..
What could be the problem?
I changed the Image to ImageButton and then added Command parameter. The key was the Jason's comment. Binding the Model property to my ImageButton's IsVisibility property and it worked correctly.
I'm trying to call a function in a Xamarin project by using the SelectionChanged property.
Inside this property, I've called a function that I've declared in the cs file.
Here is the XAML code:
<CollectionView x:Name="PCCollection" SelectionMode="Single" SelectionChanged="Cell_Tapped" AutomationId="{Binding Tipologia_Alimento}">
Here is the CS function:
private async void Cell_Tapped(object sender, System.EventArgs e) {
Console.WriteLine("Tapped");
Console.WriteLine((sender as Cell).AutomationId.ToString());
}
When I click on the Collection View cell, it prints the value "Tapped" but it gives me also the Break Mode error: "The application is in break mode".
Could you help me with this error?
Thanks in advance.
Your syntax is not valid. The Collection View control does not have AutomationId property.
Sample
<CollectionView ItemsSource="{Binding Monkeys}"
SelectionChanged="Cell_Tapped"
SelectionMode="Single">
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid Padding="10">
<Label Grid.Column="1"
Text="{Binding Name}"
FontAttributes="Bold" />
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
void Cell_Tapped(object sender, SelectionChangedEventArgs e)
{
if (((CollectionView)sender).SelectedItem == null)
return;
string current = (e.CurrentSelection.FirstOrDefault() as Monkey)?.Name;
}
You can find more here
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/collectionview/selection
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/collectionview/populate-data
I am new with xamarin, I am facing an issue in my xamarin forms project.
I have a Label and 2 images inside listview-viewcell. I want to change the label text onclick of images. Increase the label text value by 1 if click like and decrease by 1 if click unlike. I use the label x:name, but it is not accessible in class. How can i fix this?
<StackLayout>
<ListView>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Label
Text="{Binding likeCount}"
x:Name="likecount"/>
<Image Source="like.png">
<Image.GestureRecognizers>
<TapGestureRecognizer
Tapped="LikeOrUnlikeTweet"
CommandParameter="{Binding .}"
NumberOfTapsRequired="1" />
</Image.GestureRecognizers>
</Image
<Image Source="unlike.png">
<Image.GestureRecognizers>
<TapGestureRecognizer
Tapped="LikeOrUnlikeTweet"
CommandParameter="{Binding .}"
NumberOfTapsRequired="1" />
</Image.GestureRecognizers>
</Image
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
Anybody please suggest a solution with working code.
Thanks in advance
First of you need to create command in your VM and need to change as follow:
<TapGestureRecognizer
Tapped="{Binding Source={x:Reference YourListName}, Path=BindingContext.LikeOrUnlikeTweetCommand}"
CommandParameter="{Binding .}"
NumberOfTapsRequired="1" />
ViewModel Code
public ICommand LikeOrUnlikeTweetCommand { get; }
Initialise in constructor
LikeOrUnlikeTweetCommand = new Command<YourModelDto>(LikeOrUnlikeTweet);
Function code in this you change your count value and update list.
void LikeOrUnlikeTweet(YourModelDto yourModelDto)
{
....
}
I would take one of 2 paths for doing this:
Use an ObservableCollection as ItemsSource for your list, obvious when you change properties of an item they would be reflected in the list. What the list view would do is it would replace the old item with the new one modified with your new values. You can make a search about what an ObservableCollection collection is.
My actual way, as im fighting low performance of android with listviews, and this makes it: you can create a custom class for ViewCell, avoid low-speed bindings, set all properties inside your custom ViewCell by code. When the cell bindigcontext changes more likely the ItemsSource item is being assigned to your cell, so you can now take its value ans set it up.
protected override void OnBindingContextChanged()
{
SetupCell(); //assign values to named controls manually
base.OnBindingContextChanged();
}
public void SetupCell()
{
var item = BindingContext as YouItemClass;
if (item == null) return;
txtTitle.Text = item.Name;
//etc
...
i keep getting this error: Items collection must be empty before using ItemsSource, when i attempt to bind data to a Panorama control. below is my xaml snippet.
<controls:Panorama x:Name="panorama">
<controls:PanoramaItem >
<StackPanel>
<TextBlock Text="{Binding Text}"/>
</StackPanel>
</controls:PanoramaItem>
</controls:Panorama>
in my code behind (xaml.cs), i do something like this:
protected override void OnNavigatedTo(NavigationEventArgs e) {
string id = NavigationContext.QueryString["id"];
ObservableCollection<MyObject> list = DataAccessService.get(id);
panorama.ItemsSource = list;
base.OnNavigatedTo(e);
}
note that MyObject has a Text property. any help is appreciated.
after modifying it per the link below, the same exception is still thrown.
<controls:Panorama x:Name="panorama">
<controls:Panorama.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding Header}"/>
</DataTemplate>
</controls:Panorama.HeaderTemplate>
<controls:PanoramaItem >
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Text}"/>
</StackPanel>
</DataTemplate>
</controls:PanoramaItem>
</controls:Panorama>
finally, after continuing further with the user below's help, this is the solution that got rid of the exception.
<controls:Panorama x:Name="panorama">
<controls:Panorama.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding Header}"/>
</DataTemplate>
</controls:Panorama.HeaderTemplate>
<controls:Panorama.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Text}"/>
</StackPanel>
</DataTemplate>
</controls:Panorama.ItemTemplate>
</controls:Panorama>
Your problem is that you're building the Panorama in XAML as though it were static rather than preparing it to be data-bound.
Take a look at this quick tutorial for a Data Binding Panorama Control:
Data Binding Panorama Control WP7 MVVM
Notice the difference in how your XAML is being constructed for the control. Instead of setting the Items collection on the Panorama control, you need to set the HeaderTemplate and ItemTemplate so that the control knows how to render things once data is bound to it.
I have a Pivot control which I am using as following within the XAML.
I have bound the Pivot Title to a method on my view model as its content will vary depending upon what is being displayed.
<controls:Pivot x:Name="MainPivot" ItemsSource="{Binding PivotItemHeaders}" Title="{Binding ApplicationTitle}" >
<controls:Pivot.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding Description}"/>
</DataTemplate>
</controls:Pivot.HeaderTemplate>
<controls:Pivot.ItemTemplate>
<DataTemplate>
<ListBox x:Name="EventsListbox"
ItemsSource="{Binding allEventItems}"
ItemTemplate="{StaticResource EventDisplay3}"
SelectionChanged="EventsListbox_SelectionChanged"/>
</DataTemplate>
</controls:Pivot.ItemTemplate>
</controls:Pivot>
The collection of items is being refreshed and the binding is working fine for these objects - however the Pivot title is not refreshing with the new value.
It seems stuck at the value when the page/pivot control was first shown.
Any ideas how I can get the pivot control to refresh? - Thanks
I just did a quick test, binding works just fine:
<controls:Pivot Title="MY APPLICATION" ItemsSource="{Binding Items}">
<controls:Pivot.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding LineOne}" />
</DataTemplate>
</controls:Pivot.HeaderTemplate>
<controls:Pivot.ItemTemplate>
<DataTemplate>
<Grid>
<Button Content="Update" Click="Button_Click" />
</Grid>
</DataTemplate>
</controls:Pivot.ItemTemplate>
</controls:Pivot>
And in the C#
private void Button_Click(object sender, RoutedEventArgs e)
{
App.ViewModel.Items.Clear();
App.ViewModel.Items.Add(new ItemViewModel() { LineOne = "foo" });
App.ViewModel.Items.Add(new ItemViewModel() { LineOne = "bar" });
App.ViewModel.Items.Add(new ItemViewModel() { LineOne = "baz" });
}
So clearly you're doing something very wrong. Post your code and we'll take a look.
Update
Title Binding also works
XAML
<controls:Pivot Title="{Binding Title}">
<controls:PivotItem Header="first">
<Grid>
<Button Click="Button_Click" Content="OK!" />
</Grid>
</controls:PivotItem>
</controls:Pivot>
C#:
private void Button_Click(object sender, RoutedEventArgs e)
{
Title = "foobar!";
PropertyChanged(this, new PropertyChangedEventArgs("Title"));
}