Binding Xamarin XAML to code behind properties (ListView) - xamarin

I want to bind my code-behind property, which is a list, to a XAML ListView. However, my ListView is never populated and I have no idea why.
<?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="BLEPl.EvaluationPage"
Title="Evaluation">
<ContentPage.Content>
<StackLayout Padding="0,20,0,20">
<ListView HasUnevenRows="True" IsVisible="True" x:Name="TableLayout" ItemsSource="{Binding Path=SensorValues}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid>
<Label Style="{StaticResource TitleLabel}" Grid.Column="0" Grid.Row="0" Text="Zeitstempel: " />
<Label Style="{StaticResource DataLabel}" Grid.Column="1" Grid.Row="0" Text="{Binding TimeStamp}" />
<Label Style="{StaticResource TitleLabel}" Grid.Column="0" Grid.Row="1" Text="Wert: " />
<Label Style="{StaticResource DataLabel}" Grid.Column="1" Grid.Row="1" Text="{Binding Value}" />
<Label Style="{StaticResource TitleLabel}" Grid.Column="0" Grid.Row="2" Text="Sensor: " />
<Label Style="{StaticResource DataLabel}" Grid.Column="1" Grid.Row="2" Text="{Binding Sensor.Name}" />
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
</ContentPage>
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class EvaluationPage : ContentPage
{
private ObservableCollection<SensorValue> SensorValues = new ObservableCollection<SensorValue>();
public EvaluationPage ()
{
InitializeComponent ();
using (var context = new BlepContext(true))
{
var repo = new BLEPRepository(context);
SensorValues = new ObservableCollection<SensorValue>(repo.GetAllSensorValues());
}
}
}
When I run this, my ListView doesn't contain any items. I do not get errors and my app compiles fine. Am I doing something wrong here?

<ListView HasUnevenRows="True" IsVisible="True" x:Name="TableLayout" ItemsSource="{Binding SensorValues}">
you can only bind to public properties, and you need to set a BindingContext for the page
// needs to be a PUBLIC PROPERTY
public ObservableCollection<SensorValue> SensorValues { get; set; }
public EvaluationPage ()
{
InitializeComponent ();
// set the BindingContext
this.BindingContext = this;
using (var context = new BlepContext(true))
{
var repo = new BLEPRepository(context);
SensorValues = new ObservableCollection<SensorValue>(repo.GetAllSensorValues());
}
}

Related

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.

How To Display list view item pop up in xamarin form

Hello Developer I want to display pop in my page. The given image link red portion I want to display please help me out how can I do that in xamarin form
Hello Xamarin developer I have attach one image link in this question .This image red mark portion I want display on my page how can I do that
Not sure what is the content of your ListView, but here's the simple example of pop up with ListView in it, so you can adapt it as you like.
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="TestPopUp.MainPage">
<AbsoluteLayout Padding="0" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
<StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
<Button Text="Pop up!" VerticalOptions="CenterAndExpand" HorizontalOptions="Center" Clicked="Button_Clicked" />
</StackLayout>
<ContentView x:Name="popupView" BackgroundColor="Transparent" Padding="10, 0" IsVisible="false" AbsoluteLayout.LayoutBounds="0, 0, 1, 1" AbsoluteLayout.LayoutFlags="All">
<StackLayout VerticalOptions="Center" HorizontalOptions="Center">
<Frame CornerRadius="10" Padding="0" BorderColor="LightGray">
<StackLayout Orientation="Vertical" HeightRequest="300" WidthRequest="200" BackgroundColor="White">
<ListView SeparatorVisibility="None" ItemsSource="{Binding MyList}" VerticalScrollBarVisibility="Never">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Label Text="{Binding .}" />
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</Frame>
</StackLayout>
</ContentView>
</AbsoluteLayout>
</ContentPage>
C#:
public partial class MainPage : ContentPage
{
public ObservableCollection<string> MyList { get; set; } = new ObservableCollection<string>();
public MainPage()
{
InitializeComponent();
MyList.Add("Item 1");
MyList.Add("Item 2");
MyList.Add("Item 3");
MyList.Add("Item 4");
MyList.Add("Item 5");
MyList.Add("Item 6");
MyList.Add("Item 7");
BindingContext = this;
}
private void Button_Clicked(object sender, EventArgs e)
{
popupView.IsVisible = true;
}
}
This will give you output like this:
So, when you want to show this pop up, just put popupView.IsVisible = true in code behined.

Any idea how to add CarouselView indicators inside the CarouselView it self?

I am using a CarouselView to display a few views
each one of them is basically 2 StackLayouts
like so
what I have done so far is create a CarouselView with a template for both of these Stacklayouts
<CarouselView
x:Name="MyCarouselView"
IsVisible="{Binding ShouldShow}"
ItemsSource="{Binding MyItemSource}"
Scrolled="CarouselView_Scrolled">
<CarouselView.ItemTemplate>
<DataTemplate>
<ContentView>
<FlexLayout Direction="Column" JustifyContent="SpaceBetween">
<StackLayout FlexLayout.Basis="25%">
<elements:TopView Data="{Binding}"/>
</StackLayout>
<StackLayout FlexLayout.Basis="75%">
<elements:BottomView Data="{Binding}"/>
</StackLayout>
</FlexLayout>
</ContentView>
</DataTemplate>
</CarouselView.ItemTemplate>
</CarouselView>
Note: the views bind to different values but for simplicity sake, I wrote a simpler DataTemplate here.
it works fine and there is no problem in binding or anything
what I am trying to do is add indicators to show the user that there are more items and which one he is seeing now. (small circles or something like that).
the thing is I want to display them between the two views like so
Any idea of how to do it?
Any other way to achieve the wanted result is welcome as well
Please and thank you.
The easy way to implement that is using Grid to do that :
<Grid>
<!-- Place new controls here -->
<CarouselView x:Name="CustomCarouselView"
IndicatorView="indicatorView"
VerticalOptions="FillAndExpand"
>
<CarouselView.ItemTemplate>
<DataTemplate>
<StackLayout>
<ContentView BackgroundColor="LightBlue" >
<Label Text="{Binding TopViewTitle}" FontSize="Header" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" HeightRequest="250"/>
</ContentView>
<ContentView BackgroundColor="LightGray" Margin="0,80,0,0">
<Label Text="{Binding BottomViewTitle}" FontSize="Header" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" HeightRequest="250" />
</ContentView>
</StackLayout>
</DataTemplate>
</CarouselView.ItemTemplate>
</CarouselView>
<IndicatorView x:Name="indicatorView"
IndicatorsShape="Square"
IndicatorColor="LightGray"
SelectedIndicatorColor="DarkGray"
VerticalOptions="Center"
Margin="0,-150,0,0" />
</Grid>
Above is my sample xaml code ,only need to custom the Margin property of IndicatorView and bottom ContentView after binding ItemSource for CarouselView :
List<CarouselModel> carouselModels = new List<CarouselModel>();
carouselModels.Add(new CarouselModel { TopViewTitle = "first top", BottomViewTitle = "first bottom" });
carouselModels.Add(new CarouselModel { TopViewTitle = "second top", BottomViewTitle = "second bottom" });
carouselModels.Add(new CarouselModel { TopViewTitle = "third top", BottomViewTitle = "third bottom" });
CustomCarouselView.ItemsSource = carouselModels;
The effect shows as expected :
The another way you can use RelativeLayout to implement that :
<RelativeLayout>
<!-- Place new controls here -->
<CarouselView x:Name="CustomCarouselView"
IndicatorView="indicatorView"
>
<CarouselView.ItemTemplate>
<DataTemplate>
<StackLayout>
<ContentView BackgroundColor="LightBlue">
<Label Text="{Binding TopViewTitle}"
FontSize="Header"
HorizontalTextAlignment="Center"
VerticalTextAlignment="Center"
HeightRequest="250" />
</ContentView>
<ContentView BackgroundColor="LightGray"
Margin="0,80,0,0">
<Label Text="{Binding BottomViewTitle}"
FontSize="Header"
HorizontalTextAlignment="Center"
VerticalTextAlignment="Center"
HeightRequest="250" />
</ContentView>
</StackLayout>
</DataTemplate>
</CarouselView.ItemTemplate>
</CarouselView>
<IndicatorView x:Name="indicatorView"
IndicatorsShape="Square"
IndicatorColor="LightGray"
SelectedIndicatorColor="DarkGray"
RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent,Property=Width,Factor=0.5,Constant=-25}"
RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent,Property=Height,Factor=0.5,Constant=-75}"
/>
</RelativeLayout>
Here you can modify RelativeLayout.XConstraint and RelativeLayout.YConstraint of IndicatorView to set the space between two ContentView . The Margin property
of Bottom ContentView also need to set , it's effect is to show the space between two ConentView .
You can achieve this in two methods :-
Grid, where you can place both the controls in the same Grid.Row.
Assign VerticalOptions="FillAndExpand" to the CarouselView and VerticalOptions="Center" to the IndicatorView.
By Using AbsoluteLayout.
Let me know if you have more queries.
We can achieve this scenario by placing a carousel view inside the parent carousel view and providing the Indicator view for the carousel placed inside.
Also we need to bind the "Position" property of inside carousel view properly, so that indicator view points to the proper selected index. Please find the code below for reference,
Inside Xaml:
<StackLayout Padding="30">
<CarouselView x:Name="MyCarouselView"
ItemsSource="{Binding MyItemSource}"
FlowDirection="MatchParent">
<CarouselView.ItemTemplate>
<DataTemplate>
<ContentView>
<FlexLayout Direction="Column"
JustifyContent="SpaceBetween"
BackgroundColor="Pink">
<StackLayout FlexLayout.Basis="5%">
<BoxView HeightRequest="100"
WidthRequest="100"
BackgroundColor="{Binding Boxview1Color}" />
</StackLayout>
<CarouselView FlexLayout.Basis="0%"
IndicatorView="indicatorView"
IsSwipeEnabled="False"
ItemsSource="{Binding Items}"
Position="{Binding Position}">
<CarouselView.ItemTemplate>
<DataTemplate>
<Label Text="{Binding ItemText}"/>
</DataTemplate>
</CarouselView.ItemTemplate>
</CarouselView>
<IndicatorView x:Name="indicatorView"
FlexLayout.Basis="10%"
HeightRequest="10"
IndicatorsShape="Circle"
IndicatorColor="White"
SelectedIndicatorColor="DarkBlue">
</IndicatorView>
<StackLayout FlexLayout.Basis="60%">
<BoxView HeightRequest="100"
WidthRequest="100"
BackgroundColor="{Binding Boxview2Color}"/>
</StackLayout>
</FlexLayout>
</ContentView>
</DataTemplate>
</CarouselView.ItemTemplate>
</CarouselView>
</StackLayout>
Inside ViewModel:
public class MainPageViewModel
{
private ObservableCollection<MyItemSourceViewModel> _myItemSource;
public ObservableCollection<MyItemSourceViewModel> MyItemSource { get; set; }
public MainPageViewModel()
{
MyItemSource = new ObservableCollection<MyItemSourceViewModel>();
MyItemSource.Add(new MyItemSourceViewModel { Boxview1Color = Color.Red, Boxview2Color = Color.Blue, Position = 0 });
MyItemSource.Add(new MyItemSourceViewModel { Boxview1Color = Color.Green, Boxview2Color = Color.Purple, Position = 1});
MyItemSource.Add(new MyItemSourceViewModel { Boxview1Color = Color.PeachPuff, Boxview2Color = Color.Brown, Position = 2 });
var count = MyItemSource.Count;
foreach(var item in MyItemSource)
{
var itemCount = count;
var i = 0;
item.Items = new List<ItemsModel>();
while(itemCount > 0)
{
var itemModel = new ItemsModel { ItemText = i.ToString()};
item.Items.Add(itemModel);
i++;
itemCount--;
}
}
}
}
public class MyItemSourceViewModel
{
public Color Boxview1Color { get; set; }
public Color Boxview2Color { get; set; }
public int Position { get; set; }
public List<ItemsModel> Items { get; set; }
}
public class ItemsModel
{
public string ItemText { get; set; }
}
Please refer below screenshots as well:
Sample screenshot 1
Sample screenshot 2

Xamarin.Forms GestureRecognizers not working on Command

Code in the xaml page:
<StackLayout VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
<CollectionView ItemsSource="{Binding MeniElementi}">
<CollectionView.ItemsLayout>
<GridItemsLayout Orientation="Vertical"
Span="2" />
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate>
<Frame Padding="10" WidthRequest="140" HeightRequest="140">
<Frame BackgroundColor="AliceBlue" WidthRequest="120" HeightRequest="120" HasShadow="True" CornerRadius="10" Padding="10" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" >
<StackLayout>
<Image Source="http://www.clker.com/cliparts/l/u/5/P/D/A/arrow-50x50-md.png" WidthRequest="70" HeightRequest="70" >
<Image.GestureRecognizers>
<TapGestureRecognizer
Command="{Binding LoadElements}"
/>
</Image.GestureRecognizers>
</Image>
<Label Text="{Binding Title}" HeightRequest="50" WidthRequest="100" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" />
</StackLayout>
</Frame>
</Frame>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</StackLayout>
Code in xaml.cs:
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Menu: ContentPage
{
MenuViewModel viewModel = new MenuViewModel();
public Menu()
{
InitializeComponent();
BindingContext = viewModel;
}
}
Code in viewmodel.cs
public class MenuViewModel :BaseViewModel, INotifyPropertyChanged
{
public Command LoadElements { get; set; }
public ObservableCollection<Meni> MeniElementi { get; set; }
public MenuViewModel()
{
LoadElements= new Command(execute: async () => await ExecuteElements());
MeniElementi = new ObservableCollection<Meni>() {
new Meni(){Title="Transatcions" ,Picture="xxx"},
new Meni(){Title="Transatcions" ,Picture="xxx"},
};
}
async Task ExecuteElements()
{
try
{
await Application.Current.MainPage.Navigation.PushAsync(new InfoPage());
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
finally
{
}
}
LoadElements Command not fired. Loading starting menu , showing menu elements just command not working to navigate to another page. Using Xamarin.Forms.Command. On other pages working normal with Command
You could reset the binding path of the tap . So that you can handle the logic in the same command .
in the ContentPage (which contains the CollectionView)
<?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:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Name="Page" //set the name of page
x:Class="xxx.xxxPage">
<TapGestureRecognizer Command="{Binding Source={x:Reference Page},Path=BindingContext.LoadElements}"
you need to call the command on the ViewModel of the Page for that you need to do this:-
<Image.GestureRecognizers>
<TapGestureRecognizer Command="{Binding LoadElements, Source={x:Reference Name=ThisPage}}" />
</Image.GestureRecognizers>
And put x:Name="ThisPage" in the ContentPage tag of the xaml at the top of the page.
Let me know if you face difficulties.

How to display a ListView and Other Controls in a ScrollView?

I want to display a ListView and other controls inside a ScrollView. All is bound to a ViewModel. My attempts failed because it's not recommend to put a ListView inside a ScrollView. As I use a complex ViewCell DataTemplate, I did not consider to add my items in the code behind file as Buttons instead of a ListView.
Hope someone can show me a Xaml or CS pattern to achieve my goal.
Please only suggest a solution which works on iOS and Android!
Thanks
Eric
This is XAML code
<ScrollView Padding="2">
<StackLayout HorizontalOptions="FillAndExpand">
<Grid HorizontalOptions="FillAndExpand">
<StackLayout>
<ScrollView Orientation="Horizontal">
<ListView BackgroundColor="Transparent" ItemsSource="{Binding UsersList}" SeparatorVisibility="None" x:Name="YourListView" RowHeight="50">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout BackgroundColor="Transparent" Padding="5">
<Button Text="{Binding UserName}" WidthRequest="115" HorizontalOptions="FillAndExpand" TextColor="White" BackgroundColor="#4b76c4" FontAttributes="Bold" FontSize="20" FontFamily="Avenir Book"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ScrollView>
</StackLayout>
</Grid>
</StackLayout>
</ScrollView>
and .cs file you need set BindingContext
BindingContext = new YourViewModel();
Solution:
As Rodrigo E suggested I download the latest Xamarin Evolve App 2016. After digging through the code I adjusted/simplified the FeedPage.xaml in the solution to that:
<?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:XamarinEvolve.Clients.UI;assembly=XamarinEvolve.Clients.UI"
xmlns:pull="clr-namespace:Refractored.XamForms.PullToRefresh;assembly=Refractored.XamForms.PullToRefresh"
x:Class="XamarinEvolve.Clients.UI.FeedPage"
x:Name="FeedPage"
Title="Evolve Feed"
Icon="tab_feed.png"
BackgroundColor="{DynamicResource WindowBackgroundTable}">
<pull:PullToRefreshLayout
IsPullToRefreshEnabled="True"
RefreshCommand="{Binding RefreshCommand}"
IsRefreshing="{Binding IsBusy}">
<local:AlwaysScrollView
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand">
<StackLayout>
<StackLayout Spacing="0">
<local:NonScrollableListView
x:Name="ListViewSessions"
ItemsSource="{Binding Sessions}">
<local:NonScrollableListView.RowHeight>
<OnPlatform x:TypeArguments="x:Int32" Android="50" iOS="50" WinPhone="50"/>
</local:NonScrollableListView.RowHeight>
<local:NonScrollableListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Button Text="{Binding Title}" BackgroundColor="Black" TextColor="Green" />
</ViewCell>
</DataTemplate>
</local:NonScrollableListView.ItemTemplate>
</local:NonScrollableListView>
</StackLayout>
<StackLayout Padding="0" Spacing="0" BackgroundColor="Green">
<Button Text="OTHER" BackgroundColor="Blue" TextColor="White" />
<Button Text="OTHER" BackgroundColor="Blue" TextColor="White" />
<Button Text="OTHER" BackgroundColor="Blue" TextColor="White" />
<Button Text="OTHER" BackgroundColor="Blue" TextColor="White" />
<Button Text="OTHER" BackgroundColor="Blue" TextColor="White" />
<Button Text="OTHER" BackgroundColor="Blue" TextColor="White" />
</StackLayout>
</StackLayout>
</local:AlwaysScrollView>
</pull:PullToRefreshLayout>
There are a few things to do:
In the FeedViewModel.cs I added that code for a quick test:
async Task ExecuteLoadSessionsCommandAsync()
{
if (LoadingSessions)
return;
LoadingSessions = true;
try
{
NoSessions = false;
Sessions.Clear();
OnPropertyChanged("Sessions");
#if DEBUG
await Task.Delay(1000);
#endif
var sessions = await StoreManager.SessionStore.GetNextSessions();
var testSessions = new List<Session>();
testSessions.Add(new Session
{
Title = "TEST"
});
testSessions.Add(new Session
{
Title = "TEST"
});
testSessions.Add(new Session
{
Title = "TEST"
});
sessions = testSessions;
if(sessions != null)
Sessions.AddRange(sessions);
NoSessions = Sessions.Count == 0;
}
catch(Exception ex)
{
ex.Data["method"] = "ExecuteLoadSessionsCommandAsync";
Logger.Report(ex);
NoSessions = true;
}
finally
{
LoadingSessions = false;
}
}
You have to reference the package Refractored.XamForms.PullToRefresh to get the Pull-to-Refresh behavor.
This is in that namespace referenced: xmlns:pull="clr-namespace:Refractored.XamForms.PullToRefresh;assembly=Refractored.XamForms.PullToRefresh"
You have to Copy the AlwaysScrollView , NonScrollableListView to your PCL library.
refercene it with: xmlns:local="clr-namespace:"
In your iOS Project add that custom ListView Renderer:
public class NonScrollableListViewRenderer : ListViewRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs e)
{
base.OnElementChanged(e);
if (Control != null)
Control.ScrollEnabled = false;
}
}
public class AlwaysScrollViewRenderer : ScrollViewRenderer
{
public static void Initialize()
{
var test = DateTime.UtcNow;
}
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
this.AlwaysBounceVertical = true;
}
}
See file: Renderer
Put that CollectionChanged Handler in your Code-behind file:
ViewModel.Sessions.CollectionChanged += (sender, e) =>
{
var adjust = Device.OS != TargetPlatform.Android ? 1 : -ViewModel.Sessions.Count + 1;
ListViewSessions.HeightRequest = (ViewModel.Sessions.Count * ListViewSessions.RowHeight) - adjust;
};
See File FeedPage.cs.xaml: FeedPage.cs.xaml

Resources