Xamarin - how to open a new ContentPage in a ListView? - xamarin

I have a list that comes from my web service and i display it like so:
<StackLayout HorizontalOptions="FillAndExpand">
<ListView x:Name="curso" ItemSelected="CursoView_ItemSelected">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<StackLayout Orientation="Horizontal">
<StackLayout Orientation="Vertical" HorizontalOptions="FillAndExpand">
<Label StyleClass="Header" Text="{Binding name}" />
</StackLayout>
</StackLayout>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
And now i want to be able to click on an item and open a new ContentPage

public void CursoView_ItemSelected(object sender, ItemSelectedEventArgs e)
{
// this assumes your current page is already contained in a NavigationPage
Navigation.PushAsync(new MyNextPage());
}

Related

ViewCell repeated many times in Listview Xamarin

I have
Test.xaml
<ContentPage.Content>
<StackLayout>
<ListView x:Name="myCarts" HasUnevenRows="true">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Label TextColor="#848484" Text="11" />
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
Test.xaml.cs
public Test()
{
InitializeComponent();
var cartUserInfo = Preferences.Get("CartUser", "defaultcart");
myCarts.ItemsSource = cartUserInfo;
}
I checked the data in cartUserInfo Preferences only 1 line of data. Why does it repeat again in the UI?
How does it display correctly. Thank you

xamarin collectionview cell custom border

How to add custom border to the collectionview cell like the image?
<CollectionView HeightRequest="100" ItemsSource="{Binding Test}">
<CollectionView.ItemsLayout >
<GridItemsLayout Orientation="Vertical" Span="4"/>
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid >
<Image Source="{Binding Image}" ></Image>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
Put the collection view into a colored container could do that, and set margin for the collection view as the width of border, like
<StackLayout BackgroundColor="Black" HorizontalOptions="FillAndExpand">
<CollectionView Margin="4,0">
</CollectionView>
</StackLayout>
I use a sub-class frame to add border, please take a look at the following code:
Creating custom frame in .Net standard library project(shared code).
public class MyFrame : Xamarin.Forms.Frame
{
}
Custom renderer in Android platform.
[assembly: ExportRenderer(typeof(MyFrame), typeof(MyFrameRenderer))]
namespace demo3.Droid
{
[Obsolete]
class MyFrameRenderer : VisualElementRenderer<Frame>
{
public MyFrameRenderer()
{
SetBackgroundDrawable(Resources.GetDrawable(Resource.Drawable.blue_rect));
}
}
}
<ContentPage.Content>
<StackLayout HorizontalOptions="FillAndExpand">
<control:MyFrame Padding="5">
<CollectionView BackgroundColor="Transparent" ItemsSource="{Binding Test}">
<CollectionView.ItemsLayout>
<GridItemsLayout Orientation="Vertical" Span="4" />
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate>
<Frame BackgroundColor="Transparent" BorderColor="Gray">
<Label Text="{Binding .}" TextColor="Black" />
</Frame>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</control:MyFrame>
</StackLayout>
</ContentPage.Content>
The screenshot:

How to delete item from ListView in Xamarin forms

I have a ListView and I want to delete some items, I have not found a useful answer yet.
this is a XMAL :
<ListView.ItemTemplate >
<DataTemplate>
<ViewCell>
<StackLayout>
<Label Text="{Binding Name}"
Style="{DynamicResource ListItemTextStyle}" />
<Label Text="{Binding PhoneNo}"
Style="{DynamicResource ListItemDetailTextStyle}"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
and listview :
public ObservableCollection<Contact> ContactList2 { get; set; }
I can easily add it, but I do not know how to delete it.
Use a context menu
XAML
<ViewCell.ContextActions>
<MenuItem Clicked="OnDelete" CommandParameter="{Binding .}"
Text="Delete" IsDestructive="True" />
</ViewCell.ContextActions>
code behind
public void OnDelete (object sender, EventArgs e) {
var mi = ((MenuItem)sender);
Contact contact = (Contact)mi.CommandParameter;
ContactList2.Remove(contact);
}

Grouped ListView throws Index Out of Range exception when clicking outside of list in xamarin forms wpf

I have face issue with grouped listview in xamarin forms wpf application. I have used group listview in one of the pages in the application, where if I click outside of the grouped listview, the application is crashed. Please suggest any idea to fix this crash. Thank you.
exception : An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Index was out of range. Must be non-negative and less than the size of the collection.
Image :
SampleCode :
Xaml :
<StackLayout HorizontalOptions = "FillAndExpand" VerticalOptions = "FillAndExpand">
<ListView x:Name="GroupedViewM" IsGroupingEnabled="true" ItemsSource="{Binding All}" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" ItemTapped="SelectedUserorChannel">
<ListView.GroupHeaderTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" Padding="0,0,0,10">
<Label Text="{Binding Title}" TextColor="#e0e2e5" FontSize="22" VerticalTextAlignment="Center" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand"/>
<Image x:Name="AddButton" IsVisible="{Binding AddChannelBtnVisibility}" Source="add.png" HeightRequest="20" WidthRequest="20" HorizontalOptions="EndAndExpand" VerticalOptions="CenterAndExpand" Margin="0,0,10,0">
<Image.GestureRecognizers>
<TapGestureRecognizer Tapped="CreateNewChannel"/>
</Image.GestureRecognizers>
</Image>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.GroupHeaderTemplate>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
<Image Source="{Binding ProfileImage}" HorizontalOptions="Start" VerticalOptions="FillAndExpand" HeightRequest="20" WidthRequest="20"/>
<Label Text="{Binding FirstName}" TextColor="#e0e2e5" FontSize="Small" HorizontalOptions="FillAndExpand" VerticalTextAlignment="Center" VerticalOptions="FillAndExpand"/>
<Frame CornerRadius="5" BackgroundColor="#5e997c" Padding="8,0" IsVisible="{Binding MessageCountVisibility}" HorizontalOptions="EndAndExpand" VerticalOptions="CenterAndExpand">
<Label Text="{Binding MessageCount}" TextColor="White" FontSize="15" HorizontalOptions="Center" VerticalOptions="Center"/>
</Frame>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Xaml.cs
private void SelectedUserorChannel(object sender, ItemTappedEventArgs e)
{
try
{
var userModel = ((ListView)sender).SelectedItem as UserModel;
OpenUserOrGroupChat(userModel);
((ListView)sender).SelectedItem = null;
}
catch (Exception exception)
{
LoggingManager.Error(exception);
}
}
private async void CreateNewChannel(object sender, EventArgs e)
{
try
{
await Helper.NavigateToAsync(new CreateChannelView());
}
catch (Exception exception)
{
LoggingManager.Error(exception);
}
}`
Probably you are casting null with some datatype say UserModel.
i would suggest you to refactor your code with a null check in place
{
if (((ListView)sender).SelectedItem != null && ((ListView)sender).SelectedItem as UserModel userModel)
{
OpenUserOrGroupChat(userModel);
((ListView)sender).SelectedItem = null;
}
}
Try this setting Footer property of this ListView as:
<ListView x:Name="GroupedViewM" IsGroupingEnabled="true"
ItemsSource="{Binding All}"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand"
ItemTapped="SelectedUserorChannel"
Footer="">
</ListView>

Cardview in Xamarin.Forms?

Does anyone know if it's possible to create a CardView style (scrollable) list using Xamarin.Forms? We need it to render same on both iOS and Android. Also need to tweak properties like the shadow (to slightly raise each card)
Here is a nuget: https://github.com/tiger4589/Xamarin.Forms-CardView
Cardview control in Xamarin.Froms.
Install it in your shared project only and use the following import in your page's xaml:
xmlns:cardView="clr-namespace:CardView;assembly=CardView"
Just use the control in viewcell of your listview.
Example screenshot: each card is a row in listview
Following code is an usage example of above control:
<ListView
x:Name="listView"
Margin="0,8,0,0"
HasUnevenRows="True"
ItemTapped="Handle_ItemTapped"
ItemsSource="{Binding HouseholdDetail}"
SeparatorVisibility="None">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Padding="8,8,8,8" Orientation="Vertical">
<cardView:CardView
BackgroundColor="White"
CardViewHasShadow="True"
HeightRequest="220">
<cardView:CardView.CardViewContent>
<StackLayout
Padding="10"
HorizontalOptions="Center"
Spacing="10"
VerticalOptions="Center">
<Image HeightRequest="96" Source="{Binding Image}" />
<BoxView
HeightRequest="1"
WidthRequest="275"
Color="LightGray" />
<Grid>
<Label
Grid.Row="0"
Grid.Column="0"
Margin="15,0,0,0"
FontSize="Medium"
Text="{Binding FullName}" />
<Label
Grid.Row="0"
Grid.Column="1"
Margin="0,0,15,0"
FontSize="Medium"
HorizontalTextAlignment="End"
Text="{Binding Relation}" />
</Grid>
<BoxView
HeightRequest="1"
WidthRequest="275"
Color="LightGray" />
<Grid>
<Label
Grid.Row="0"
Grid.Column="0"
Margin="15,0,0,0"
FontSize="Medium"
Text="{Binding LeavesAt}" />
<Label
Grid.Row="0"
Grid.Column="1"
Margin="0,0,15,0"
FontSize="Medium"
HorizontalTextAlignment="End"
Text="{Binding ArrivesAt}" />
</Grid>
</StackLayout>
</cardView:CardView.CardViewContent>
</cardView:CardView>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Here you may notice the freedom you have such as you can define to have shadow or not and design the whole layout of cardview using Xamarin default layouts.
Why not use a frame? i am put inside at the listview, a frame with grid.
and do something like this to get the style cardview you like.
public class CardView : Frame
{
public CardView()
{
if (Device.OS == TargetPlatform.iOS)
{
HasShadow = false;
OutlineColor = Color.Transparent;
BackgroundColor = Color.Transparent;
}
if (Device.OS == TargetPlatform.Android)
{
HasShadow = true;
OutlineColor = Color.Transparent;
BackgroundColor = Color.Transparent;
}
}
}
No need Third party library
it is support scrollable and pullrefresh
<StackLayout>
<ListView x:Name="ItemsListView"
ItemsSource="{Binding Items}"
VerticalOptions="FillAndExpand"
HasUnevenRows="true"
RefreshCommand="{Binding LoadItemsCommand}"
IsPullToRefreshEnabled="true"
IsRefreshing="{Binding IsBusy, Mode=OneWay}"
CachingStrategy="RecycleElement"
ItemSelected="OnItemSelected">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Padding="10">
<Frame HasShadow="True" >
<StackLayout>
<Label Text="{Binding Text}"
LineBreakMode="NoWrap"
FontSize="16" />
<Label Text="{Binding Description}"
LineBreakMode="NoWrap"
FontSize="16" />
</StackLayout>
</Frame>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>

Resources