Xamarin forms select carousel item - c#

I am learning Xamarin, I would like to get the value of the carousel item selected. I cannot add ItemSelected as in a listview.
Here my Xaml code :
<CarouselView x:Name="NewsList" >
<CarouselView.ItemTemplate >
<DataTemplate>
<StackLayout>
<Frame HasShadow="True"
BorderColor="DarkGray"
CornerRadius="5"
Margin="20"
HeightRequest="300"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand">
<StackLayout>
<Label Text="{Binding NewsName}"
FontAttributes="Bold"
FontSize="Large"
HorizontalOptions="Center"
VerticalOptions="Center" />
<Image Source="{Binding NewsImageUrl}"
Aspect="Fill"
HeightRequest="150"
WidthRequest="150"
HorizontalOptions="Center" />
<Label Text="{Binding ProviderAndDate}"
HorizontalOptions="Center" />
</StackLayout>
</Frame>
</StackLayout>
</DataTemplate>
</CarouselView.ItemTemplate>
</CarouselView>
Here is the function I would like to use once my item is selected: Get the value of NewsName and ProviderAndDate
private void OnFrameTapped(object sender, EventArgs e)
{
Console.WriteLine("SelectedNewsName" + "SelectedNewsProviderAndDate");
}
Thanks for your help

CarouselView is sort of a different control when it comes to visualization and events than a ListView so you will have to come up with sort of a different solution too
The easiest way to do something similar to a selected item event here would need customization from your side to add the event in.
A good workaround would be just using the CurrentItem property or passing a CommandParameter on the Tap of a Frame!
<StackLayout>
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Command="{Binding CarouselItemTapped,Source={x:Reference currentPage}}" CommandParameter="{Binding .}"/>
</StackLayout.GestureRecognizers>
<Frame ...... />
And then give your current contentpage a x:Name
<ContentPage ..... X:Name="currentPage"
Now in your xaml.cs
Public ICommand CarouselItemTapped{ get; set; }
In the Constructor:
CarouselItemTapped= new Xamarin.Forms.Command((selectItem)=>{//Perform action here});
Feel free to get back if you have questions
More about Commands: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/data-binding/commanding
More about CarouselView: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/carouselview/

Late but it might help someone. The one who is using BindingContext to bind the data, they can get tapped model as shown below.
private void OnFrameTapped(object sender, EventArgs e)
{
var frame = sender as Frame;
var x = frame.BindingContext as YOURMODEL;
}

Related

How to handle touch event for a FlexLayout in Xamarin

So Im building an app where I should show multiple products, since I want to show more than just one product in one row, i couldn't use a ListView, so I thought about using a FlexLayout as a Bindable-Layout and use the ItemsSource to display my list of products, whiche was a sucess. So I wanted to add a touch event to each of my products shown in the flexlayout, to do so I created a new Behaviour, this is the link for the code I used :
https://gist.github.com/jtaubensee/96a5e49c66a205e36ff32787f1d2114d
that did work and therefor I can use a Command. my problem is that I want to get the product that was clicked, and I can't figure out how to do ? is there anyone who can possibly help me with that ?
If you are not adverse to xaml, this is how I handle it.
<FlexLayout BindableLayout.ItemsSource="{Binding Abilities}" IsVisible="{Binding HasAbilities}" BindableLayout.ItemTemplate="{DataTemplate attitm:AttachedAbility}"
AlignItems="Center" Wrap="Wrap" JustifyContent="Center"/>
and the template implements the touch gesture, and passes the object as the Command Parameter;
<ContentView.Content>
<StackLayout Padding="20,8" HorizontalOptions="Center">
<Frame BorderColor="{OnPlatform Android=DarkCyan, UWP=Accent}" Padding="4">
<Frame.GestureRecognizers>
<TapGestureRecognizer Command="{Binding DrillIntoCommand}" CommandParameter="{Binding}"/>
</Frame.GestureRecognizers>
<StackLayout HorizontalOptions="Center" Orientation="Horizontal">
<Label x:Name="TitleLabel" Text="{Binding Title}" HorizontalOptions="Center" VerticalOptions="Center"/>
<Label Text="" FontFamily="{StaticResource FontAwesomeSolid}" IsVisible="{Binding IsUserCreated}" TextColor="Orange" HorizontalOptions="Center"/>
</StackLayout>
</Frame>
</StackLayout>
</ContentView.Content>

View.ContextActions not firing to code behind Clicked

Problem:
After following a few examples, one, two, three, I am not able to get my ContextActions to connect to my Code Behind.
This is from the examples. MenuItem_Clicked is not connecting the XAML to the code behind
<ViewCell.ContextActions>
<MenuItem Clicked="MenuItem_Clicked" Text="TEST" Command="{Binding .}"/>
</ViewCell.ContextActions>
Setup:
I am just working with a basic example i found online. it is not a MVVM. I have the ListItems_Refresh action setup and working.
Goal of the Code:
When the users clicks a row, I want to open the default browser and go to the URL from the row.
I would love to know how i can troubleshoot this issue or if i have glaring typo. Thanks in advance
Code:
XAML
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:HelloWorld"
x:Class="HelloWorld.MainPage">
<StackLayout Margin="20">
<Label Text="60 Second Sports" FontAttributes="Bold" HorizontalOptions="Center"/>
<ListView x:Name="rssList" IsPullToRefreshEnabled="True" Refreshing="ListItems_Refreshing">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.ContextActions>
<MenuItem Clicked="MenuItem_Clicked" Text="TEST" Command="{Binding .}"/>
</ViewCell.ContextActions>
<StackLayout>
<Label Text="{Binding Title}" Font="8"/>
<!--<Label Text="{Binding Description}" Font="6"/>-->
<Label Text="{Binding PublishedDate}" Font="5"/>
<Label Text="{Binding Link}" Font="5"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage>
Code Behind
private void MenuItem_Clicked(object sender, EventArgs e)
{
Console.WriteLine("button was clicked");
System.Diagnostics.Process.Start("http://google.com");
}
protected void ListItems_Refreshing(object sender, EventArgs e)
{
Console.WriteLine("refresh triggered");
//doRefresh();
//my method for repopulating the list ImageListView.EndRefresh();
//this is a very important step. It will refresh forever without triggering it }
}
If you want to open a browser when you click on a ListView item, you can just listen to the ItemTapped event.
ItemTapped fires when an item is tapped.
So, in your ListView
<ListView x:Name="rssList" IsPullToRefreshEnabled="True"
ItemTapped="listItemTapped"
Refreshing="ListItems_Refreshing">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Label Text="{Binding Title}" Font="8"/>
<!--<Label Text="{Binding Description}" Font="6"/>-->
<Label Text="{Binding PublishedDate}" Font="5"/>
<Label Text="{Binding Link}" Font="5"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
And, the listener method.
public void listItemTapped(object sender, ItemTappedEventArgs e)
{
Console.WriteLine("button was clicked");
var item = (YourModel)e.Item;
}

Xamarin Listview with grouping won't scroll

I'm working on my first Xamarin app. I want to make a listview with grouping and it succeeded. The only problem I have that it won't scroll. My other listview on another page scrolls without a problem, but my listview with grouping won't do that. I tried this both on an Android simulator as on my Android phone (I don't have a macbook or something to test on iOS), and it won't scroll on either of them. I looked it up but a lot of people put the listview in a scrollview, and I didn't do that.
This is my XAML code:
<StackLayout Margin="10" Orientation="Vertical">
<Label Text="{Binding Title}" FontAttributes="Bold"
FontSize="20" HorizontalOptions="CenterAndExpand" />
<Label Text="{Binding Subtitle}" FontAttributes="Italic"
FontSize="15" HorizontalOptions="CenterAndExpand" />
<ListView HasUnevenRows="True" SeparatorColor="Accent"
VerticalOptions="FillAndExpand" IsEnabled="False"
IsGroupingEnabled="True" GroupDisplayBinding="{Binding Key}"
ItemsSource="{Binding ScansGroup}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Spacing="4">
<StackLayout Orientation="Horizontal" Margin="10,7,10,1">
<Label Text="{Binding Location, StringFormat='{0}'}"
FontAttributes="Bold" FontSize="16" />
<Label Text="{Binding DateTime, StringFormat='{0:dd/MM/y HH:mm}'}"
HorizontalOptions="EndAndExpand" />
</StackLayout>
<StackLayout Orientation="Horizontal">
<Label Text="{Binding ElapsedTimeOnLocation}"
HorizontalOptions="Start"
Margin="10,0,10,7" />
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
I put it in an MVVM structure, and the grouping I did with a MVVM helper that I got from here https://channel9.msdn.com/Shows/XamarinShow/The-Xamarin-Show-12-MVVM-Helpers .
My code behind that is meant for the grouping is the following:
public ObservableRangeCollection<Grouping<string, ScanViewModel>> ScansGroup { get; } =
new ObservableRangeCollection<Grouping<string, ScanViewModel>>();
void Group()
{
var grouped = from scan in Scans
group scan by scan.Day into scanGroup
select new Grouping<string, ScanViewModel>(scanGroup.Key, scanGroup);
ScansGroup.ReplaceRange(grouped);
}
The grouping shows perfectly and the list too. The only problem is that
I can't scroll. Can someone help me?
I've figured it out. There's nothing wrong with your grouping. In your code you set IsEnabled="False" to the ListView. It makes the listview's scroll ability to be handled just if you drag from an enabled item inside the ListView, and even thus, the scroll is like belittled and with a very bad user experience.
Just set your ListView like this:
<ListView HasUnevenRows="True"
SeparatorColor="Accent"
VerticalOptions="FillAndExpand"
IsEnabled="True"
IsGroupingEnabled="True"
GroupDisplayBinding="{Binding Key}"
ItemsSource="{Binding ScansGroup}">
...
</ListView>
I can't tell you if it was designed to be this way, or if it 's a bug, but it is the cause of your issue.
It's probable you have done this to handle some unwanted behavior. If so, let us know what is specifically your intend with this IsEnabled="False", then we'll be able to help you with this.
I hope it helps you.
You didn't add the template for the group. Add this in the <ListView>
<ListView.GroupHeaderTemplate >
<DataTemplate >
<ViewCell Height="28" >
<Label Text="{Binding GroupName}" VerticalTextAlignment="Center" HorizontalOptions="Start" />
</ViewCell>
</DataTemplate>
</ListView.GroupHeaderTemplate>
Also, in the code bend or ViewModel, you need to bind to a group class of the items you want in the list such as:
public class GroupDetails : ObservableCollection<SomeItemsToShow>
{
public string GroupName { get; set; }
}
Check out this Example for more details:
https://xamarinhelp.com/xamarin-forms-listview-grouping/

TableView Viewcell Tapped action

How do I make use of the Tapped action in the ViewCell to navigate to other page?
Xmal codes
<TableView Intent="Settings" HasUnevenRows="true" VerticalOptions="StartAndExpand" BackgroundColor="White" >
<TableRoot>
<TableSection>
<ViewCell Height="100" Tapped="OnProfileClicked">
<ViewCell.View>
<StackLayout Orientation="Horizontal" Padding="5,2,5,2" BackgroundColor="White" >
<Image x:Name="ImgProfile" HeightRequest="100"/>
<Label x:Name="btnName" VerticalOptions="Center" TextColor="Black" FontSize="20"/>
<Label Text="> " FontSize="15" HorizontalOptions="EndAndExpand" VerticalOptions="Center"/>
</StackLayout>
</ViewCell.View>
</ViewCell>
</TableSection>
</TableRoot>
</TableView>
CS File
public void onProfileTapped()
{
Navigation.PushAsync(new Clubs());
}
so there are a couple things that are wrong with your code.
1.) You wrote Tapped=OnProfileClicked but the method you actually made is called onProfileTapped(), this is a mismatch
2.) The parameters for your item tapped event are wrong, most Xamarin events contain a sender and eventArgs.
Here's how you can fix your code to make it work:
void OnProfileClicked (object sender, System.EventArgs e) { //your code}
Also, tip, when you push a page using Navigation. You might want mark the method as async and await the action to make sure it's a smooth transition.

Xamarin Forms ListView does not update correctly

I'm working with Xamarin Forms and MVVMLight.
So I'm displaing a List of "Patients" with a ListView. Each Element of the ListView has a Delete-Button. When clicked the Patient is deleted from the List and the View is notified with RaisePropertyChanged().
The Problem now is that when I add multiple Patients and then want to delete one. Always the last one is removed in the View. I debugged the App and saw that the right one is delted from my List. But when the View updates its data, always the last Entry is removed.
<ListView ItemsSource="{Binding Patients}" HasUnevenRows="true" x:Name="Patientlist">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<StackLayout Orientation="Horizontal" VerticalOptions="FillAndExpand">
<StackLayout HorizontalOptions="FillAndExpand">
<Label Text="Patient" Style="{DynamicResource TitleStyle}"/>
<Label Text="Benötigte Proben"/>
<Label Text="Untersuchungen"/>
<Button Text="Bearbeiten" />
</StackLayout>
<StackLayout HorizontalOptions="FillAndExpand">
<Label Text="{Binding PatientID}"/>
<Label Text="Test"/>
<Label Text="Test"/>
<Button Text="Löschen" Command="{Binding DelCMD}"/>
</StackLayout>
</StackLayout>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
So this is my ListView. The Button "Löschen" ist the delete-Button. It executes the following Command:
private RelayCommand delCMD;
public RelayCommand DelCMD
{
get
{
return delCMD ?? (delCMD = new RelayCommand (()=>Messenger.Default.Send<PatientM> (this, "delPat")));
}
}
This code is in my PatientModel-Class. And sends a Message to the VM where the Element is removed.
public void delPatient(PatientM Patient)
{
Patients.Remove (Patient);
RaisePropertyChanged ("Patientlist");
}
This code is then executed in the VM. An well like I said the right Patient is removed from the List (Patients.Remove). But after RaisePropertyChanged is called the wrong is Element is delted in the View. Always the last one even tough I deleted another on in the List.

Categories

Resources