StackLayout GestureRecognizers Effects - xamarin

I wanted to add some effects to the StackLayout GestureRecognizers so the user know they have selected the button but I don't see a way to do it? I have tried to change the BackgroundColor for the StackLayout but that is not working.
Can I change the BackgroundColor or is there a long hold event I can use ?
xaml code
<StackLayout VerticalOptions="Center"
x:Name="slpatient"
Grid.Row="4"
BackgroundColor="#8cb8e1"
Orientation="Horizontal">
<StackLayout.GestureRecognizers>
<TapGestureRecognizer NumberOfTapsRequired="1" Tapped="Button_Clicked" />
</StackLayout.GestureRecognizers>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="50"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Image Source="user_34.png"
Grid.Column="1"
VerticalOptions="Center" />
<Label Text="Click me to change the BackgroundColor!"
Grid.Column="2"
TextColor="White"
LineBreakMode="WordWrap"
VerticalOptions="FillAndExpand"
VerticalTextAlignment="Center"/>
</Grid>
</StackLayout>
cs code
private void Button_Clicked_Clicked(object sender, System.EventArgs e)
{
slpatient.BackgroundColor = Color.Black;
var masterDetailPage = Application.Current.MainPage as MasterDetailPage;
masterDetailPage.Detail = new NavigationPage((new SearchPage("DrugName")));
}

The change color functionality is likely happening on a non-UI thread. So you could potentially enclose it in Device.BeginInvokeOnMainThread so it gets called in the UI thread, as shown:
Device.BeginInvokeOnMainThread(() =>
{
slpatient.BackgroundColor = Color.Black;
});
To answer your second question, yes you can add a timer too:
private void Button_Clicked_Clicked(object sender, System.EventArgs e)
{
slpatient.BackgroundColor = Color.Black;
var masterDetailPage = Application.Current.MainPage as MasterDetailPage;
Device.StartTimer(TimeSpan.FromSeconds(10), () =>
{
masterDetailPage.Detail = new NavigationPage((new SearchPage("DrugName")));
return false; // True = Repeat again, False = Stop the timer
});
}

I have tried to change the BackgroundColor for the StackLayout but that is not working.
If you want to change background color, I suggest you can consider to use Xameffects, you can install xameffects from nuget packages. Changing TouchEffect.Color.
<ContentPage
x:Class="App4.Page21"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:xe="clr-namespace:XamEffects;assembly=XamEffects">
<ContentPage.Content>
<StackLayout
xe:TouchEffect.Color="Red"
HorizontalOptions="Center"
VerticalOptions="Center">
<Button
x:Name="btn1"
Clicked="Btn1_Clicked"
HorizontalOptions="Center"
Text="btn1"
VerticalOptions="Center" />
</StackLayout>
</ContentPage.Content>
More detailed info, you can take a look:
https://github.com/mrxten/XamEffects

Related

FindByName control inside another control on ContentPage in Xamarin

I want to set focus on SearchBar when he appears. The problem is that SearchBar is placed inside of popup view and I need to access him from ViewModel.
In standard way I would use
Xamarin.Forms.SearchBar tmp_SearchBar = this.Page.FindByName("fro_SearchBar_NewItem") as Xamarin.Forms.SearchBar;
but that's not working anymore.
Here is XAML
<sfPopup:SfPopupLayout x:Name="fro_Popup_NewItem" Opened="fro_Popup_NewItem_Opened" Grid.Row="1" HorizontalOptions="Center" VerticalOptions="Center" BackgroundColor="Black">
<sfPopup:SfPopupLayout.PopupView>
<sfPopup:PopupView BackgroundColor="Black" WidthRequest ="400" HeightRequest ="100" ShowFooter="False" ShowHeader="False">
<sfPopup:PopupView.ContentTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<!--Search bar-->
<Grid Grid.Row="0" HorizontalOptions="Center" VerticalOptions="Center">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<SearchBar x:Name="fro_SearchBar_NewItem"
Grid.Column="0"
Text="{Binding SearchText_Popup, Mode=TwoWay}"
SearchCommand="{Binding SearchCommand}"
Placeholder="Find"
CancelButtonColor="White"
TextColor="White"
PlaceholderColor="Gray"/>
</Grid>
</Grid>
</DataTemplate>
</sfPopup:PopupView.ContentTemplate>
</sfPopup:PopupView>
</sfPopup:SfPopupLayout.PopupView>
</sfPopup:SfPopupLayout>
Nested FindByName doesn't work either.
Syncfusion.XForms.PopupLayout.SfPopupLayout tmp_Popup = _Page.FindByName("fro_Popup_NewItem") as Syncfusion.XForms.PopupLayout.SfPopupLayout;
Xamarin.Forms.SearchBar tmp_SearchBar = tmp_Popup.FindByName("fro_SearchBar_NewItem") as Xamarin.Forms.SearchBar;
Thanks
You can use Task to open a new thread to complete this operation in code-behind.
Xaml:
<SearchBar x:Name="fro_SearchBar_NewItem" Placeholder="...." BackgroundColor="White"/>
Code behind:
public partial class PagePop : Popup
{
public PagePop()
{
InitializeComponent();
Task.Run(() => myTask());//Create and start the thread
}
private void myTask()
{
Thread.Sleep(300);
fro_SearchBar_NewItem.Focus();
}
}
It seems that this wasn't so far from right direction, neither of the comments actually.
Syncfusion.XForms.PopupLayout.SfPopupLayout tmp_Popup = _Page.FindByName("fro_Popup_NewItem") as Syncfusion.XForms.PopupLayout.SfPopupLayout;
Xamarin.Forms.SearchBar tmp_SearchBar = tmp_Popup.FindByName("fro_SearchBar_NewItem") as Xamarin.Forms.SearchBar;
but I found the one which works and I don't have to create separate XAML for Popup.
private void fro_Popup_NewItem_Opened(object sender, EventArgs e)
{
try
{
var nativeObject = (object)fro_Popup_NewItem.GetType().GetRuntimeProperties().FirstOrDefault(x => x.Name.Equals("NativeObject")).GetValue(fro_Popup_NewItem);
var formsPopupviewContentTemplate = nativeObject.GetType().GetRuntimeFields().FirstOrDefault(x => x.Name.Equals("formsPopupViewContentTemplate")).GetValue(nativeObject);
var SearchBar = (formsPopupviewContentTemplate as Grid).FindByName<SearchBar>("fro_SearchBar_NewItem");
SearchBar?.Focus();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Thanks for help, everyone.

Xamarin App opens different Page from Navigation.PushAsync() Page

Description
Xamarin application opens different Page upon NavigationPage.Pushaync().
NavigationPage.Asyncpush() is called within a ButtonClicked Method.
That different page used to be the one being pushed but it no longer is.
ViewModel.cs
private async void OnAboutUsClicked()
{
var modifiedContactUs = new ModifiedContactUs() { BackgroundColor = ResourceColourModel.BackgroundColor };
await Application.Current.MainPage.Navigation.PushAsync(modifiedContactUs);
}
ModifiedContactUs.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"
x:Class="Project.Views.Pages.ModifiedContact"
xmlns:mapObject="clr-namespace:Xamarin.Forms.Maps;assembly=Xamarin.Forms.Maps">
<ContentPage.Content>
<StackLayout>
<Grid BackgroundColor="white">
<mapObject:Map x:Name="mapId" HasZoomEnabled="True" MapType="Street">
</mapObject:Map>
</Grid>
</StackLayout>
</ContentPage.Content>
</ContentPage>
ModifiedContactUs.xaml.cs
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Project.Views.Pages
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ModifiedContactUs : ContentPage
{
public ModifiedContactUs()
{
InitializeComponent();
}
}
ContactUs.xaml(The different Page)
<?xml version="1.0" encoding="utf-8" ?>
<customControl:CustomContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:map ="clr-namespace:Xamarin.Forms.Maps;assembly=Xamarin.Forms.Maps"
xmlns:ffimageloading="clr-namespace:FFImageLoading.Svg.Forms;assembly=FFImageLoading.Svg.Forms"
xmlns:customControl="clr-namespace:Project.CustomControls.Renderers"
xmlns:templates_navbar="clr-namespace:Project.Views.Templates.Menus"
xmlns:fontAwesome="clr-namespace:Project._Utilities"
mc:Ignorable="d"
x:Class="Project.Views.Pages.ContactUs"
>
<ContentPage.Content>
<StackLayout BackgroundColor="Transparent" Spacing="0">
<templates_navbar:NavBar DotMenu_IsVisible="False" BackButton_IsVisible="True"/>
<Grid BackgroundColor="white">
<Grid.RowDefinitions>
<RowDefinition Height=".33*"/>
<RowDefinition Height=".07*"/>
<RowDefinition Height=".6*"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width=".7*"/>
<ColumnDefinition Width=".3*"/>
</Grid.ColumnDefinitions>
<StackLayout Grid.Column="0" Padding="10">
<StackLayout>
<Label
Text="Company Name"
FontAttributes="Bold"
FontSize="Medium"
FontFamily="Lato-Bold"
VerticalOptions="CenterAndExpand"
HorizontalOptions="StartAndExpand"
/>
<Label
Text="{Binding Address}"
FontFamily="Lato-Bold"
VerticalOptions="CenterAndExpand"
HorizontalOptions="StartAndExpand"
/>
</StackLayout>
<StackLayout>
<Label
Text="Opening Times"
FontAttributes="Bold"
FontSize="Medium"
FontFamily="Lato-Bold"
VerticalOptions="CenterAndExpand"
HorizontalOptions="StartAndExpand"
/>
<Label
x:Name="weekdays_lbl"
Text="{Binding Weekday}"
FontFamily="Lato-Bold"
VerticalOptions="CenterAndExpand"
HorizontalOptions="StartAndExpand"
/>
<Label
x:Name="weekend_lbl"
Text="{Binding Weekend}"
FontFamily="Lato-Bold"
VerticalOptions="CenterAndExpand"
HorizontalOptions="StartAndExpand"
/>
</StackLayout>
</StackLayout>
<StackLayout Grid.Column="1">
<StackLayout VerticalOptions="CenterAndExpand">
<Button
x:Name="CallUsBtn"
Text="Call Us"
TextColor="White"
BackgroundColor="{StaticResource PrimaryColour}"
FontFamily="Lato-Bold"
FontSize="12"
BorderWidth="2"
BorderColor="White"
Margin="1"
CornerRadius="22"
Command="{Binding PhoneCommand}"
/>
<Button
x:Name="MessageUsBtn"
Text="Message"
TextColor="White"
BackgroundColor="{StaticResource PrimaryColour}"
FontFamily="Lato-Bold"
FontSize="12"
BorderWidth="2"
BorderColor="White"
Margin="1"
CornerRadius="22"
Command="{Binding EmailCommand}"
/>
<Button
x:Name="RequestCallBack"
Text="Request CallBack"
TextColor="White"
BackgroundColor="{StaticResource AccentColour}"
FontFamily="Lato-Bold"
FontSize="11"
BorderWidth="2"
BorderColor="White"
Margin="1"
CornerRadius="22"
Command="{Binding CallbackCommand}"
/>
</StackLayout>
</StackLayout>
</Grid>
<Grid Grid.Row="1" Padding="5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width=".25*"/>
<ColumnDefinition Width=".25*"/>
<ColumnDefinition Width=".25*"/>
<ColumnDefinition Width=".25*"/>
</Grid.ColumnDefinitions>
<StackLayout Grid.Column="0">
<Grid VerticalOptions="CenterAndExpand">
<Image
Source="{FontImage FontFamily={StaticResource MaterialFontFamily},
Glyph={x:Static fontAwesome:IconFonts.Facebook}, Color=#1877F2,Size=60}"
HeightRequest="80"
/>
<Button Clicked="SocialMediaBtnHandler" BackgroundColor="Transparent" Margin="5, 0" CommandParameter="facebook"/>
</Grid>
</StackLayout>
<StackLayout Grid.Column="1">
<Grid VerticalOptions="CenterAndExpand">
<Image
Source="{FontImage FontFamily={StaticResource MaterialFontFamily},
Glyph={x:Static fontAwesome:IconFonts.Twitter}, Color=#00ACED, Size=60}"/>
<Button Clicked="SocialMediaBtnHandler" BackgroundColor="Transparent" Margin="5, 0" CommandParameter="twitter"/>
</Grid>
</StackLayout>
<StackLayout Grid.Column="2">
<Grid VerticalOptions="CenterAndExpand">
<Image
Source="{FontImage FontFamily={StaticResource MaterialFontFamily},
Glyph={x:Static fontAwesome:IconFonts.Linkedin}, Color=#0E76A8, Size=60}"/>
<Button Clicked="SocialMediaBtnHandler" BackgroundColor="Transparent" Margin="5, 0" CommandParameter="linkedIn"/>
</Grid>
</StackLayout>
<StackLayout Grid.Column="3">
<Grid VerticalOptions="CenterAndExpand" Padding="2">
<ffimageloading:SvgCachedImage
Source="social_logo_instagram.png"
HeightRequest="40"/>
<Button Clicked="SocialMediaBtnHandler" BackgroundColor="Transparent" Margin="5, 0" CommandParameter="instagram"/>
</Grid>
</StackLayout>
</Grid>
<Grid Grid.Row="2">
<Grid>
<StackLayout Grid.Row="0" Padding="5">
<map:Map x:Name="mapObject" HasZoomEnabled="True" MapType="Street">
<map:Map.ItemTemplate>
<DataTemplate>
<map:Pin
Position="{Binding Position}"
Address="{Binding Address}"
Label="{Binding PlaceName}"
/>
</DataTemplate>
</map:Map.ItemTemplate>
</map:Map>
</StackLayout>
</Grid>
</Grid>
</Grid>
<AbsoluteLayout BackgroundColor="Red" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" AbsoluteLayout.LayoutBounds="0, 0, 1, 1" AbsoluteLayout.LayoutFlags="SizeProportional">
</AbsoluteLayout>
</StackLayout>
</ContentPage.Content>
</customControl:CustomContentPage>
ContactUs.xaml.cs (The different page)
using Project._SharedData;
using Project.CustomControls.Renderers;
using Project.Models;
using Project.ViewModels;
using Rg.Plugins.Popup.Services;
using System;
using Xamarin.Essentials;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
using Xamarin.Forms.Xaml;
namespace Project.Views.Pages
{
[XamlCompilation(XamlCompilationOptions.Compile)]
[System.ComponentModel.DesignTimeVisible(false)]
public partial class ContactUsPage : CustomContentPage
{
ContactUsVM _ContactUsVM;
public ContactUsPage()
{
InitializeComponent();
BindingContext = _ContactUsVM = new ContactUsVM();
initMap();
configureDisplay();
setFontOpeningTime();
}
protected override void OnAppearing()
{
base.OnAppearing();
_ContactUsVM.OnAppearing();
configureDisplay();
}
protected override void OnDisappearing()
{
base.OnDisappearing();
_ContactUsVM.OnDisappearing();
try
{
if (PopupNavigation.Instance != null)
PopupNavigation.Instance.PopAsync(true);
}
catch (Exception) { }
}
private void setFontOpeningTime()
{
DayOfWeek day = DateTime.Now.DayOfWeek;
// Set the font based on whether current day is weekday or weekend
if ((day == DayOfWeek.Saturday) || (day == DayOfWeek.Sunday))
{
weekend_lbl.FontAttributes = FontAttributes.Bold;
}
else
{
weekdays_lbl.FontAttributes = FontAttributes.Bold;
}
}
private void configureDisplay()
{
if (!string.IsNullOrEmpty(SharedPrefs.UserSessionEmail))
{
RequestCallBack.IsVisible = true;
MessageUsBtn.Text = "Email";
}
else
{
RequestCallBack.IsVisible = false;
MessageUsBtn.Text = "Message";
}
}
private async void SocialMediaBtnHandler(object sender, EventArgs e)
{
string socialMediaName = (sender as Button).CommandParameter.ToString().ToLower();
await Launcher.OpenAsync(SocialMediaModel.WebLink(socialMediaName));
}
private void initMap()
{
try
{
double latitude = Convert.ToDouble(SharedData.CompanyDetailsList[0].Latitude);
double longitude = Convert.ToDouble(SharedData.CompanyDetailsList[0].Longitude);
mapObject.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(latitude, longitude), Distance.FromMeters(100)));
mapObject.ItemsSource = SharedData.CompanyDetailsList;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
Expected behavior
To navigate to a new Page named ModifiedContactUs
Actual behavior:
Navigates to page called named ContactUs
Basic Information:
Android Build:
-minimum level 21
-Target level 30
Devices:
-Huawei Y6 2019
-API level 29
-Pixel 5
-API level 30
Notes
This question is different to from the first question I asked recently (Where the device crashes). This is behavior happens on all devices I test on except the one from that first question
Expected behavior
To navigate to a new Page named ModifiedContactPage
Actual behavior:
Navigates to page called named ContactUsPage
From your code I saw you just push to ModifiedContactUs not ModifiedContactPage .
var modifiedContactUs = new ModifiedContactUs() { BackgroundColor = ResourceColourModel.BackgroundColor };
await Application.Current.MainPage.Navigation.PushAsync(modifiedContactUs);
Suggestion
Try to add breakpoint to see if it triggers button click event es expected .
Delete the old class and try again .
Delete the app from the device and try again .
This worked: Clone the repo into a new folder as a new project and copy the files and changes to this new repo.
Attempted configuration solutions that did not work: Restarting visual studio. Untick and Tick Debug Mode. Untick and tick Deploy in Configuration Manager under Build. In Android Properties> android Options making sure debugging is checked and debugger is Xamarin.

Xamarin - how to make background transparent?

I have a simple page with a black background. I would like to make it transparent so that the page below is visible but blurred.
Someone suggest :
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:NameSpace"
x:Class="NameSpace.MainPage"
BackgroundColor="Transparent"> </ContentPage>
Another one suggest:
<StackLayout VerticalOptions="End" HorizontalOptions="FillAndExpand" BackgroundColor="#80000000" Opacity="0.5" HeightRequest="160" Grid.Row="2" >
So both work on tablets but not on mobile devices. Could someone explain to me why and / or suggest me how to solve it? Thanks in advance
You could use AbsoluteLayout and set the transparent of the "float" view .
<AbsoluteLayout>
<!--below view-->
<StackLayout BackgroundColor="Red" AbsoluteLayout.LayoutBounds="0,0,1,1" AbsoluteLayout.LayoutFlags="All" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
<Button Text="111111" />
</StackLayout>
<!--float view-->
<StackLayout BackgroundColor="Gray" Opacity="0.5" AbsoluteLayout.LayoutBounds="0.5,0,1,0.5" AbsoluteLayout.LayoutFlags="All" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
</StackLayout>
</AbsoluteLayout>
Update
It is impossible to implement it if use Navigation . Because it is not enough to set the backgroundColor of Page . There are Rendering layers in the ContentPage .
As a workaround , we could simulate a navigation (open a new page) .
<AbsoluteLayout>
<!--below view-->
<StackLayout BackgroundColor="Red" AbsoluteLayout.LayoutBounds="0,0,1,1" AbsoluteLayout.LayoutFlags="All" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
<Button Text="open new page" Clicked="Button_Clicked_1"/>
</StackLayout>
<!--float view-->
<StackLayout x:Name="FloatView" BackgroundColor="Gray" Opacity="0.5" AbsoluteLayout.LayoutBounds="1,1,0.01,1" AbsoluteLayout.LayoutFlags="All" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
<Label Text="this is a transparent view" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" />
<Button Text="Back" Clicked="Button_Clicked"/>
</StackLayout>
</AbsoluteLayout>
private void Button_Clicked_1(object sender, EventArgs e)
{
//show
Device.BeginInvokeOnMainThread(async () =>
{
var xPosition = 0;
var currentPosition = 0.9;
while (currentPosition >xPosition)
{
await Task.Delay(1);
currentPosition -= 0.04;
AbsoluteLayout.SetLayoutBounds(FloatView, new Rectangle(currentPosition,0, 1, 1));
}
});
}
private void Button_Clicked(object sender, EventArgs e)
{
//hide
Device.BeginInvokeOnMainThread(async () =>
{
AbsoluteLayout.SetLayoutBounds(FloatView, new Rectangle(1, 0, 0.01, 0.01));
});
}

error in my Navigation. PushAsync (new DetailsPage (monkey))

I'm following the following example of carousel with the listview, more when I go to open Navigation.PushAsync the item in the listview is called only the first item, on all items clicked his name only the first item, a position error?
void Handle_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var monkey = ((ListView)sender).SelectedItem as Monkey;
if (monkey == null)
return;
Navigation.PushAsync(new DetailsPage(monkey));
}
https://blog.xamarin.com/flip-through-items-with-xamarin-forms-carouselview/
EDIT
MonkeysPage.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"
x:Class="Monkeys.Views.MonkeysPage"
xmlns:design="clr-namespace:Monkeys;assembly=Monkeys"
xmlns:controls="clr-namespace:ImageCircle.Forms.Plugin.Abstractions;assembly=ImageCircle.Forms.Plugin.Abstractions"
xmlns:cv="clr-namespace:Xamarin.Forms;assembly=Xamarin.Forms.CarouselView"
BindingContext="{x:Static design:ViewModelLocator.MonkeysViewModel}"
x:Name="MonkeysPage"
Title="Traditional Monkeys">
<ContentPage.Content>
<ListView ItemsSource="{Binding MonkeysGrouped}"
ItemSelected="Handle_ItemSelected"
HasUnevenRows="true"
GroupShortNameBinding = "{Binding Key}"
IsGroupingEnabled = "true"
GroupDisplayBinding = "{Binding Key}">
<ListView.Header>
<cv:CarouselView x:Name="CarouselZoos" ItemsSource="{Binding Path=BindingContext.Zoos, Source={x:Reference MonkeysPage}}" HeightRequest="200">
<cv:CarouselView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Image Grid.RowSpan="2" Aspect="AspectFill" Source="{Binding ImageUrl}"/>
<StackLayout Grid.Row="1" BackgroundColor="#80000000" Padding="12">
<Label TextColor="White" Text="{Binding Name}" FontSize="16" HorizontalOptions="Center" VerticalOptions="CenterAndExpand"/>
</StackLayout>
</Grid>
</DataTemplate>
</cv:CarouselView.ItemTemplate>
</cv:CarouselView>
</ListView.Header>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid Padding="10" RowSpacing="10" ColumnSpacing="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<controls:CircleImage
BorderColor="Aqua"
BorderThickness="3"
HeightRequest="66"
HorizontalOptions="CenterAndExpand"
VerticalOptions="CenterAndExpand"
Aspect="AspectFill"
WidthRequest="66"
Grid.RowSpan="2"
Source="{Binding Image}"/>
<Label Grid.Column="1"
Text="{Binding Name}"
VerticalOptions="End"/>
<Label Grid.Column="1"
Grid.Row="1"
VerticalOptions="Start"
Text="{Binding Location}"/>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
MonkeysPage.xaml.cs
public MonkeysPage()
{
InitializeComponent();
BindingContext = new MonkeysViewModel();
}
async void Handle_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var monkey = e.SelectedItem as Monkey;
if (monkey == null)
return;
await Navigation.PushAsync(new DetailsPage(monkey)); // always await Navigations
((ListView)sender).SelectedItem = null;
}
DetailsPage.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"
x:Class="Monkeys.Views.DetailsPage"
xmlns:design="clr-namespace:Monkeys;assembly=Monkeys"
xmlns:controls="clr-namespace:ImageCircle.Forms.Plugin.Abstractions;assembly=ImageCircle.Forms.Plugin.Abstractions"
BindingContext="{x:Static design:ViewModelLocator.DetailsViewModel}"
Title="{Binding Monkey.Name}">
<ContentPage.Content>
<ScrollView>
<StackLayout Padding="10">
<controls:CircleImage
BorderColor="Aqua"
BorderThickness="3"
HeightRequest="200"
WidthRequest="200"
HorizontalOptions="CenterAndExpand"
Aspect="AspectFill"
Source="{Binding Monkey.Image}"/>
<Label Text="{Binding Monkey.Name}" FontAttributes="Bold"/>
<Label Text="{Binding Monkey.Location}" FontSize="Micro"/>
<Label Text="{Binding Monkey.Details}" FontSize="Large"/>
</StackLayout>
</ScrollView>
</ContentPage.Content>
DetailsPage
public partial class DetailsPage : ContentPage
{
public DetailsPage(Monkey monkey)
{
InitializeComponent();
}
}
You're doing everything good except that you forgot to reset the SelectedItem to null, that's why you are getting always the first list item clicked.
Your code should look like this:
async void Handle_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var monkey = e.SelectedItem as Monkey;
if (monkey == null)
return;
await Navigation.PushAsync(new DetailsPage(monkey)); // always await Navigations
((ListView)sender).SelectedItem = null;
}
P.S. Make your method async so you don't cause UI Thread to block
EDIT
Try to get the selected item from SelectedItemChangedEventArgs.
var monkey = e.SelectedItem as Monkey;
UPDATE
Okay the SelectedItem is being updated successfully but the 'Monkey Item' on the ViewModel behind the DetailsPage is not!
So on DetailsPage add this line:
public partial class DetailsPage : ContentPage
{
public DetailsPage(Monkey monkey)
{
InitializeComponent();
BindingContext = new DetailsViewModel(monkey); // Update the BindingContext
}
}
And remove this line on the DetailsPage.xaml:
BindingContext="{x:Static design:ViewModelLocator.DetailsViewModel}"

How to do ItemClick on HorizontalListView in Xamarin.Forms

https://www.nuget.org/packages/HorizontalListView1.1/
I used the above link and implemented Horizontal List. List is coming, it's scrolling horizontally. But, for Item click, I used two properties:
SelectedItem
SelectedItemChanged
But, still I did not get that how to do Item Click Event in this.
See the below code:
XAML:
<ScrollView Orientation="Horizontal" ><StackLayout Orientation="Horizontal">
<Controls:HorizontalListView x:Name="packages_listname" ListOrientation="Horizontal" >
<Controls:HorizontalListView.ItemTemplate SelectedItemChanged="Item_Changes">
<DataTemplate>
<Grid Grid.ColumnSpacing="0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<StackLayout Orientation="Horizontal" Grid.Row="0" BackgroundColor="#282C2B" HeightRequest="60" Spacing="0" Padding="0" Margin="0">
<Label Text="{Binding Package_Name}" HorizontalTextAlignment="Start" VerticalTextAlignment="Center" TextColor="White" Margin="0"/>
</StackLayout>
</Grid>
</DataTemplate>
</Controls:HorizontalListView.ItemTemplate>
</Controls:HorizontalListView>
</StackLayout>
</ScrollView>
</StackLayout>
Code.Cs:
packages_listname.ItemsSource = packageslist;
public void Item_Changes(object sender, EventArgs e){
// var obj = ((HorizontalListView)sender).SelectedItem as PackagesModelClass;
var obj = packages_listname.SelectedItem as PackagesModelClass;
switch (obj.Package_Name)
{
case "Corporate":
list_of_corporate.ItemsSource = GetData("Corporate");
break;
case "ValueAddGrid":
list_of_corporate.ItemsSource = GetData("ValueAddGrid");
break;
case "UtilityGrid":
list_of_corporate.ItemsSource = GetData("UtilityGrid");
break;
}
}

Resources