I have a page with a collection view. I have a button that allows the user to generate a pdf from the collection view data and share the pdf. the generation process takes a few seconds because there is a lot of data so I thought I should show something like a progress bar or progress ring to keep the user waiting and do nothing during this process. I tried to show something like a pop up using content view. this is the code: of the content view:
<ContentView x:Name="popupLoadingView" BackgroundColor="Transparent" Padding="10, 0" IsVisible="false" HorizontalOptions="Center" VerticalOptions="Center">
<StackLayout VerticalOptions="Center" HorizontalOptions="Center">
<StackLayout Orientation="Vertical" HeightRequest="150" WidthRequest="200" BackgroundColor="White">
<ActivityIndicator x:Name="activityIndicator" Margin="0,50,0,0" VerticalOptions="Center" HorizontalOptions="Center" Color="Black" WidthRequest="30" HeightRequest="30" ></ActivityIndicator>
<Label x:Name="lblLoadingText" TextColor="Black" VerticalOptions="Center" HorizontalOptions="Center" VerticalTextAlignment="Center" Text="Loading..."></Label>
</StackLayout>
</StackLayout>
</ContentView>
and this is the code of my collection view
<?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="isc_alphaApp.Inventory">
<ContentPage.ToolbarItems >
<ToolbarItem Order="Secondary"
Text="logout"
Priority="2"
/>
</ContentPage.ToolbarItems>
<ContentPage.Resources>
<Style TargetType="Grid">
<Setter Property="VisualStateManager.VisualStateGroups">
<VisualStateGroupList>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal" />
<VisualState x:Name="Selected">
<VisualState.Setters>
<Setter Property="BackgroundColor"
Value="#ffc40c" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateGroupList>
</Setter>
</Style>
</ContentPage.Resources>
<ContentPage.Content>
<StackLayout >
<SearchBar HorizontalOptions="FillAndExpand" x:Name="search" BackgroundColor="#ffc40c"/>
<CollectionView x:Name="lstl"
SelectionChanged="lstl_SelectionChanged"
SelectionMode="Single"
>
<CollectionView.Header>
<Grid Padding="2" ColumnSpacing="1" RowSpacing="1" >
<Grid.RowDefinitions>
<RowDefinition Height="35" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.5*" />
<ColumnDefinition Width="0.7*" />
<ColumnDefinition Width="0.3*"/>
<ColumnDefinition Width="0.5*" />
<ColumnDefinition Width="0.5*" />
</Grid.ColumnDefinitions>
<Label Grid.Column="0"
Text="Code"
FontAttributes="Bold"
LineBreakMode="TailTruncation"
HorizontalOptions="Center"
VerticalOptions="Center"
TextColor="Black"/>
<Label Grid.Column="1"
Text="Description"
FontAttributes="Bold"
LineBreakMode="TailTruncation"
HorizontalOptions="Center"
VerticalOptions="Center"
TextColor="Black"/>
<Label
TextColor="Black"
Grid.Column="2"
Text="Unit"
LineBreakMode="TailTruncation"
FontAttributes="Bold"
HorizontalOptions="Center"
VerticalOptions="Center"
/>
<Label
Grid.Column="3"
Text="Qty"
LineBreakMode="TailTruncation"
FontAttributes="Bold"
HorizontalOptions="Center"
TextColor="Black"
VerticalOptions="Center"
/>
<Label
TextColor="Black"
Grid.Column="4"
Text="U.Price"
LineBreakMode="TailTruncation"
FontAttributes="Bold"
HorizontalOptions="Center"
VerticalOptions="Center"
/>
</Grid>
</CollectionView.Header>
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid Padding="1" ColumnSpacing="1" RowSpacing="0">
<Grid.RowDefinitions>
<RowDefinition Height="40" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.5*" />
<ColumnDefinition Width="0.7*" />
<ColumnDefinition Width="0.3*" />
<ColumnDefinition Width="0.5*" />
<ColumnDefinition Width="0.5*" />
</Grid.ColumnDefinitions>
<Label HorizontalOptions="Center"
Grid.Column="0"
TextColor="Black"
Text="{Binding itemcode}"
VerticalOptions="Center"
LineBreakMode="TailTruncation" />
<Label
Grid.Column="1"
VerticalOptions="Center"
HorizontalOptions="Center"
TextColor="Black"
Text="{Binding name}"
LineBreakMode="TailTruncation" />
<Label
Grid.Column="2"
TextColor="Black"
Text="{Binding itemsunitcode}"
LineBreakMode="TailTruncation"
VerticalOptions="Center"
HorizontalOptions="Center"
FontAttributes="Italic"
/>
<Label
TextColor="Black"
Grid.Column="3"
VerticalOptions="Center"
HorizontalOptions="Center"
Text="{Binding currentQuantity}"
LineBreakMode="TailTruncation"
FontAttributes="Italic"
/>
<Label
Grid.Column="4"
TextColor="Black"
Text="{Binding CostPrice}"
LineBreakMode="TailTruncation"
VerticalOptions="Center"
HorizontalOptions="Center"
FontAttributes="Italic"
/>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
<StackLayout VerticalOptions="EndAndExpand" HorizontalOptions="FillAndExpand" Orientation="Horizontal" BackgroundColor="#ffc40c">
<StackLayout Style="{StaticResource ButtonNavigationBarStackLayoutStyle}" x:Name="stckcol">
<Image Margin="0,10,0,10" x:Name="imgAdd" Style="{StaticResource ButtonNavigationBarImageStyle}" />
<Label Text="del" Style="{StaticResource ButtonNavigationBarLabelStyle}" x:Name="col_add_remove"></Label>
</StackLayout>
<StackLayout Style="{StaticResource ButtonNavigationBarStackLayoutStyle}" x:Name="stckfilter">
<Image Margin="0,10,0,10" x:Name="imgfilter" Style="{StaticResource ButtonNavigationBarImageStyle}" />
<Label Text="Filter" Style="{StaticResource ButtonNavigationBarLabelStyle}"></Label>
</StackLayout>
<StackLayout Style="{StaticResource ButtonNavigationBarStackLayoutStyle}" x:Name="stckshare">
<Image Margin="0,10,0,10" x:Name="imgshare" Style="{StaticResource ButtonNavigationBarImageStyle}" />
<Label Text="Share" Style="{StaticResource ButtonNavigationBarLabelStyle}"></Label>
</StackLayout>
</StackLayout>
</StackLayout>
</ContentPage.Content>
</ContentPage>
i tried adding the content view code at the beginning of the collection view code, but it doesn't appear in the place intended. i want it to appear like an alert on top of the collection view layout and in the middle of the screen. this is the code of the pdf generation:
shareTap.Tapped += (sender, e) =>
{
popupLoadingView.IsVisible = true;
activityIndicator.IsRunning = true;
requestPermission();
};
async public void requestPermission()
{
var newstatus= Plugin.Permissions.Abstractions.PermissionStatus.Unknown;
var status = Plugin.Permissions.Abstractions.PermissionStatus.Unknown;
status = await CrossPermissions.Current.CheckPermissionStatusAsync<StoragePermission>();
if (status != Plugin.Permissions.Abstractions.PermissionStatus.Granted)
{
newstatus = await CrossPermissions.Current.RequestPermissionAsync<StoragePermission>();
if (newstatus == Plugin.Permissions.Abstractions.PermissionStatus.Granted)
{
generatePdf();
}
}
else
{
generatePdf();
}
}
private void generatePdf()
{
try
{
PdfDocument document = new PdfDocument();
//Add a new PDF page.
PdfPage page = document.Pages.Add();
//Get the font file as stream.
Stream fontStream = typeof(MainPage).GetTypeInfo().Assembly.GetManifestResourceStream("isc_alphaApp.Assets.arial.ttf");
//Create a new PdfTrueTypeFont instance.
PdfTrueTypeFont font = new PdfTrueTypeFont(fontStream, 14);
//Create a new bold stylePdfTrueTypeFont instance.
PdfTrueTypeFont boldFont = new PdfTrueTypeFont(fontStream, 14, PdfFontStyle.Bold);
page.Graphics.DrawString("Items", boldFont, PdfBrushes.Black, PointF.Empty);
//Create PdfGrid.
PdfGrid pdfGrid = new PdfGrid();
List<items_display> list_pdf = new List<items_display>();
for (int i = 0; i < list_total.Count; i++)
{
list_pdf.Add(new items_display { Code = list_total[i].itemcode, Description = list_total[i].name, Unit = list_total[i].itemsunitcode, Qty = list_total[i].currentQuantity, Price = list_total[i].CostPrice });
}
//Add values to list
List<items_display> data = list_pdf;
//Add list to IEnumerable.
IEnumerable<items_display> dataTable = data;
PdfStringFormat format_eng = new PdfStringFormat();
format_eng.TextDirection = PdfTextDirection.LeftToRight;
format_eng.Alignment = PdfTextAlignment.Center;
//Assign data source.
pdfGrid.DataSource = dataTable;
pdfGrid.Headers[0].Cells[0].StringFormat = format_eng;
pdfGrid.Headers[0].Cells[1].StringFormat = format_eng;
pdfGrid.Headers[0].Cells[2].StringFormat = format_eng;
pdfGrid.Headers[0].Cells[3].StringFormat = format_eng;
pdfGrid.Headers[0].Cells[4].StringFormat = format_eng;
//Assign bold font to pdfGrid header.
pdfGrid.Headers[0].Style.Font = boldFont;
//Assign font to PdfGrid.
pdfGrid.Style.Font = font;
Regex regex = new Regex("[\u0600-\u06ff]|[\u0750-\u077f]|[\ufb50-\ufc3f]|[\ufe70-\ufefc]");
//Create String format with RTL text direction and center text alignment.
PdfStringFormat format = new PdfStringFormat();
format.TextDirection = PdfTextDirection.RightToLeft;
format.Alignment = PdfTextAlignment.Center;
for (int i = 0; i < data.Count; i++)
{
if (regex.IsMatch(data[i].Code))
{
pdfGrid.Rows[i].Cells[0].StringFormat = format;
}
else
{
pdfGrid.Rows[i].Cells[0].StringFormat = format_eng;
}
if (regex.IsMatch(data[i].Description))
{
pdfGrid.Rows[i].Cells[1].StringFormat = format;
}
else
{
pdfGrid.Rows[i].Cells[1].StringFormat = format_eng;
}
if (regex.IsMatch(data[i].Unit))
{
pdfGrid.Rows[i].Cells[2].StringFormat = format;
}
else
{
pdfGrid.Rows[i].Cells[2].StringFormat = format_eng;
}
pdfGrid.Rows[i].Cells[3].StringFormat = format_eng;
pdfGrid.Rows[i].Cells[4].StringFormat = format_eng;
}
//Assign string format to draw RTL text with center alsignment
//pdfGrid.Rows[0].Cells[1].StringFormat = format;
//pdfGrid.Rows[1].Cells[1].StringFormat = format;
//Draw grid to the page of PDF document.
pdfGrid.Draw(page, new Syncfusion.Drawing.PointF(0, 20));
String file_Path;
string path = DependencyService.Get<getpath>().path();
file_Path = System.IO.Path.Combine(path.ToString(), "items.pdf");
FileStream stream = new FileStream(file_Path, FileMode.Create);
document.Save(stream);
//Close the document
document.Close(true);
Share.RequestAsync(new ShareFileRequest
{
Title = "Share PDF",
File = new ShareFile(file_Path)
});
}
catch(Exception exp)
{
DisplayAlert("No Space", "Not Enough Storage!", "Okay");
}
}
The place where I try to make the content view visible doesn't seem to be right too because it is not displayed until the pdf is already generated. I want it to appear once the user clicks the button.
You would need to make some changes to make it work
You need to use an AbsoluteLayour or Grid on your Inventory page. Because they allow "Stacking" views one on top of the other. Also here you need to add your loading screen.
If your popupLoadingView is in another XAML, you need to add it to your page
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local=" <Insert your namespace here"
x:Class="isc_alphaApp.Inventory">
<!-- Rest of your code-->
<ContentPage.Content>
<Grid>
<local:popupLoadingView IsTrue="False" x:name="popupLoadingView"/>
<StackLayout>
<!-- Your collectionView goes here-->
</StackLayout>
</Grid>
</ContentPage.Content>
After doing all the pdf work, remember to turn the Visibility to false
shareTap.Tapped += (sender, e) =>
{
popupLoadingView.IsVisible = true;
//Do all the work that you need
popupLoadingView.IsVisible=false;
}
Related
i have a collectionview with data that i get from sql server database using a web api. the collcetionview populates successfully. now i wanted to add a footer to display the total of debit and credit columns. but i couldn't make it work. this is the code of my 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="isc_alphaApp.account_details">
<ContentPage.Content>
<AbsoluteLayout Padding="0" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
<StackLayout BackgroundColor="Beige" AbsoluteLayout.LayoutBounds="0, 0, 1, 1" AbsoluteLayout.LayoutFlags="All">
<StackLayout HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand">
<Label HorizontalOptions="CenterAndExpand" Margin="20,20" FontAttributes="Bold" TextColor="Black" Text="" x:Name="acc_curlabel"/>
<CollectionView x:Name="accountdetailslst" Footer="{Binding}">
<CollectionView.Header>
<Grid Padding="2" ColumnSpacing="1" RowSpacing="1" >
<Grid.RowDefinitions>
<RowDefinition Height="35" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.45*" />
<ColumnDefinition Width="0.2*" />
<ColumnDefinition Width="0.2*"/>
<ColumnDefinition Width="0.5*" />
<ColumnDefinition Width="0.35*" />
<ColumnDefinition Width="0.35*" />
<ColumnDefinition Width="0.35*" />
</Grid.ColumnDefinitions>
<Label Grid.Column="0"
Text="Date"
FontAttributes="Bold"
FontSize="14"
LineBreakMode="TailTruncation"
HorizontalOptions="Center"
VerticalOptions="Center"
TextColor="Black"/>
<Label Grid.Column="1"
Text="Jv#"
FontAttributes="Bold"
LineBreakMode="TailTruncation"
FontSize="14"
HorizontalOptions="Center"
VerticalOptions="Center"
TextColor="Black"/>
<Label
TextColor="Black"
Grid.Column="2"
FontSize="14"
Text="Ref"
LineBreakMode="TailTruncation"
FontAttributes="Bold"
HorizontalOptions="Center"
VerticalOptions="Center"
/>
<Label
Grid.Column="3"
FontSize="14"
Text="Description"
LineBreakMode="TailTruncation"
FontAttributes="Bold"
HorizontalOptions="Center"
TextColor="Black"
VerticalOptions="Center"
/>
<Label
FontSize="14"
TextColor="Black"
Grid.Column="4"
Text="Debit"
LineBreakMode="TailTruncation"
FontAttributes="Bold"
HorizontalOptions="Center"
VerticalOptions="Center"
/>
<Label
FontSize="14"
TextColor="Black"
Grid.Column="5"
Text="Credit"
LineBreakMode="TailTruncation"
FontAttributes="Bold"
HorizontalOptions="Center"
VerticalOptions="Center"
/>
<Label
TextColor="Black"
Grid.Column="6"
FontSize="14"
Text="Balance"
LineBreakMode="TailTruncation"
FontAttributes="Bold"
HorizontalOptions="Center"
VerticalOptions="Center"
/>
</Grid>
</CollectionView.Header>
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid Padding="1" ColumnSpacing="1" RowSpacing="0">
<Grid.RowDefinitions>
<RowDefinition Height="40" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.45*" />
<ColumnDefinition Width="0.2*" />
<ColumnDefinition Width="0.2*" />
<ColumnDefinition Width="0.5*" />
<ColumnDefinition Width="0.35*" />
<ColumnDefinition Width="0.35*" />
<ColumnDefinition Width="0.35*" />
</Grid.ColumnDefinitions>
<Label HorizontalOptions="Center"
Grid.Column="0"
TextColor="Black"
Text="{Binding jvdate}"
VerticalOptions="Center"
LineBreakMode="TailTruncation"
FontSize="12"/>
<Label
Grid.Column="1"
VerticalOptions="Center"
HorizontalOptions="Center"
TextColor="Black"
Text="{Binding jvnbr}"
FontSize="12"
LineBreakMode="TailTruncation" />
<Label
Grid.Column="2"
TextColor="Black"
Text="{Binding jvref}"
LineBreakMode="TailTruncation"
VerticalOptions="Center"
HorizontalOptions="Center"
FontAttributes="Italic"
/>
<Label
TextColor="Black"
Grid.Column="3"
VerticalOptions="Center"
HorizontalOptions="Center"
Text="{Binding desc}"
FontSize="12"
LineBreakMode="TailTruncation"
FontAttributes="Italic"
/>
<Label
Grid.Column="4"
TextColor="Black"
Text="{Binding jvdebit}"
FontSize="12"
LineBreakMode="TailTruncation"
VerticalOptions="Center"
HorizontalOptions="Center"
FontAttributes="Italic"
/>
<Label
Grid.Column="5"
TextColor="Black"
Text="{Binding jvcredit}"
LineBreakMode="TailTruncation"
VerticalOptions="Center"
FontSize="12"
HorizontalOptions="Center"
FontAttributes="Italic"
/>
<Label
Grid.Column="6"
TextColor="Black"
Text="{Binding balance}"
LineBreakMode="TailTruncation"
FontSize="12"
VerticalOptions="Center"
HorizontalOptions="Center"
FontAttributes="Italic"
/>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
<CollectionView.FooterTemplate >
<DataTemplate>
<Grid Padding="2" ColumnSpacing="1" RowSpacing="1" x:Name="gridfooter" >
<Grid.RowDefinitions>
<RowDefinition Height="35" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.45*" />
<ColumnDefinition Width="0.2*" />
<ColumnDefinition Width="0.2*"/>
<ColumnDefinition Width="0.5*" />
<ColumnDefinition Width="0.35*" />
<ColumnDefinition Width="0.35*" />
<ColumnDefinition Width="0.35*" />
</Grid.ColumnDefinitions>
<Label Grid.Column="3"
Text="{Binding total}"
FontAttributes="Bold"
x:Name="total"
FontSize="14"
LineBreakMode="TailTruncation"
HorizontalOptions="Center"
VerticalOptions="Center"
TextColor="Black"/>
<Label Grid.Column="4"
x:Name="totaldebit"
Text="{Binding Totjvdebit}"
FontAttributes="Italic"
FontSize="12"
LineBreakMode="TailTruncation"
HorizontalOptions="Center"
VerticalOptions="Center"
TextColor="Black"/>
<Label Grid.Column="5"
Text="{Binding Totjvcredit}"
FontAttributes="Bold"
FontSize="14"
LineBreakMode="TailTruncation"
HorizontalOptions="Center"
VerticalOptions="Center"
TextColor="Black"/>
<Label Grid.Column="6"
Text="{Binding Totbalance}"
FontAttributes="Bold"
FontSize="14"
LineBreakMode="TailTruncation"
HorizontalOptions="Center"
VerticalOptions="Center"
TextColor="Black"/>
</Grid>
</DataTemplate>
</CollectionView.FooterTemplate>
</CollectionView>
<StackLayout VerticalOptions="EndAndExpand" HorizontalOptions="FillAndExpand" Orientation="Horizontal" BackgroundColor="#ffc40c">
<StackLayout Style="{StaticResource ButtonNavigationBarStackLayoutStyle}" x:Name="stckcol">
<Image Margin="0,10,0,10" x:Name="imgAdd" Style="{StaticResource ButtonNavigationBarImageStyle}" />
<Label Text="del" Style="{StaticResource ButtonNavigationBarLabelStyle}" x:Name="col_add_remove"></Label>
</StackLayout>
<StackLayout Style="{StaticResource ButtonNavigationBarStackLayoutStyle}" x:Name="stckfilter">
<Image Margin="0,10,0,10" x:Name="imgfilter" Style="{StaticResource ButtonNavigationBarImageStyle}" />
<Label Text="Filter" Style="{StaticResource ButtonNavigationBarLabelStyle}"></Label>
</StackLayout>
<StackLayout Style="{StaticResource ButtonNavigationBarStackLayoutStyle}" x:Name="stckshare">
<Image Margin="0,10,0,10" x:Name="imgshare" Style="{StaticResource ButtonNavigationBarImageStyle}" />
<Label Text="Share" Style="{StaticResource ButtonNavigationBarLabelStyle}"></Label>
</StackLayout>
</StackLayout>
</StackLayout>
</StackLayout>
<ContentView x:Name="popupLoadingView" BackgroundColor="Transparent" Padding="10, 0" IsVisible="false" AbsoluteLayout.LayoutBounds="0, 0, 1, 1" AbsoluteLayout.LayoutFlags="All">
<StackLayout VerticalOptions="Center" HorizontalOptions="Center">
<StackLayout Orientation="Vertical" HeightRequest="150" WidthRequest="200" BackgroundColor="Transparent">
<ActivityIndicator x:Name="activityIndicator" Margin="0,50,0,0" VerticalOptions="Center" HorizontalOptions="Center" Color="Black" WidthRequest="40" HeightRequest="40" ></ActivityIndicator>
</StackLayout>
</StackLayout>
</ContentView>
</AbsoluteLayout>
</ContentPage.Content>
</ContentPage>
this is the code of my xaml.cs
public partial class account_details : ContentPage
{
List<accountdetails> listacc_collection = new List<accountdetails>();
public string total = "";
public account_details(string acc, string cur, string accname)
{
InitializeComponent();
BindingContext = this;
imgAdd.Source = ImageSource.FromResource("isc_alphaApp.remove_ic.png");
imgfilter.Source = ImageSource.FromResource("isc_alphaApp.filter_ic.png");
imgshare.Source = ImageSource.FromResource("isc_alphaApp.share_icon.png");
loadData(acc,cur,accname);
}
async private void loadData(string account, string curr,string acc_name )
{
acc_curlabel.Text = account + " - " + curr + " - " + acc_name;
popupLoadingView.IsVisible = true;
activityIndicator.IsRunning = true;
HttpClient client = new HttpClient();
string url = "http://192.168.43.99/siteisc/api/values";
string uri = url + "/getaccountdetails";
try
{
HttpResponseMessage response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode == true)
{
string content = await response.Content.ReadAsStringAsync();
var listacc_details = JsonConvert.DeserializeObject<List<allaccountdetails>>(content);
var list_filtered = listacc_details.FindAll(x => x.JvAccount == account && x.CurrencyCode == curr);
decimal blnce_row = 0;
List<String> l = new List<String>();
for (int i = 0; i < list_filtered.Count; i++)
{
blnce_row = decimal.Parse(list_filtered[i].JvDebit.ToString()) - decimal.Parse(list_filtered[i].Jvcredit.ToString()) + blnce_row;
decimal rnd_blnce = Math.Round(blnce_row, 2);
l.Add(rnd_blnce.ToString());
}
l.ToArray();
for (int i = 0; i < list_filtered.Count; i++)
{
listacc_collection.Add(new accountdetails { desc = list_filtered[i].JvDescription, jvnbr = list_filtered[i].jvnbr.ToString(), jvcredit = list_filtered[i].Jvcredit.ToString(), jvdate = DateTime.Parse(list_filtered[i].JvDate).ToString(("dd-M-yyyy")), jvdebit = list_filtered[i].JvDebit.ToString(), jvref = list_filtered[i].jvref1, balance = l[i] });
}
var list_acc_footer = new List<footeraccount>();
list_acc_footer.Add(new footeraccount { total = "Total in" + " " + curr, Totjvdebit = getTotal_dbt(listacc_collection), Totjvcredit = getTotal_crdt(listacc_collection),Totbalance= getTotal_dbt(listacc_collection) - getTotal_crdt(listacc_collection) });
accountdetailslst.ItemsSource = listacc_collection;
total = "Total in" + " " + curr;
popupLoadingView.IsVisible = false;
activityIndicator.IsRunning = false;
}
else
{
await DisplayAlert("Operation Failed", "Response Failed!", "Cancel");
}
}
catch (System.Net.WebException exp)
{
await DisplayAlert("Connection Failed", "Please Check Your Internet Connection!", "Cancel");
}
}
}
}
i tried to do something similar to the code in this link https://www.c-sharpcorner.com/article/xamarin-forms-using-listview-headertemplate-and-footertemplate-to-display-data/ but it didn't work. this is what i did:
footer.cs
public class footer
{
public List<accountdetails> GetAll { get; private set; }
public footer()
{
GetAll=new List<accountdetails> { new accountdetails { jvdate = "sksj", jvnbr = "idjd", desc = "kjsjs", balance = "ksjh", jvcredit = "4", jvdebit = "3", jvref = "jy" } };
}
}
AccountViewModel.cs:
public class AccountViewModel
{
public string total = "";
public List<accountdetails> items { get; private set; }
public AccountViewModel()
{
var service = new footer();
items = service.GetAll;
total = service.GetAll.Count.ToString();
}
}
}
and in the xaml.cs i just wrote this:
public account_details(string acc, string cur, string accname)
{
InitializeComponent();
BindingContext = new AccountViewModel();
}
but it didn't work. nothing appeared in my footer. what should i do?
thanks in advance
Original Poster (rana hd) says in a comment on the question, that making those fields properties worked.
E.g. what was this in the view model:
public string total = "";
Needed to be changed to this:
public string total { get; set; } = "";
Good afternoon.
I am using a CollectionView in Xamarin forms 5.0
I already succed to "transfert" 2 or more items from one CollectionView to an other one in the same window using SelectionMode="Multiple".
For my test, i just use and customize a good example founded on the web: https://github.com/CrossGeeks/DragAndDropXFSample
What i'm trying to do concern the appearance of the dragged items.
Because i add a DragGestureRecognizer inside my CollectionView.ItemTemplate.DataTemplate
on my first collection view and a DropGestureRecognizer inside my CollectionView.ItemTemplate.DataTemplate second collection view, the drag & drop functionnality work well.
But, the animation draw only the item i touched, not all the selected ones.
Does anybody has an idea to manage that ?
Is it even possible?
Anyway, thanks for reading and maybe your help ;-)
The xaml page:
<?xml version="1.0" encoding="UTF-8" ?>
<ContentPage
x:Class="DragAndDropXFSample.EventsPage"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
<ContentPage.Content>
<StackLayout Padding="20,40" BackgroundColor="Black">
<Label
FontAttributes="Bold"
FontSize="Large"
Text="Hi John" />
<Label Text="Your schedule Today" />
<Frame Margin="0,20,0,0" BackgroundColor="White">
<StackLayout>
<CollectionView
x:Name="EventsCollection"
ItemsSource="{Binding Events}"
SelectionMode="Multiple">
<CollectionView.EmptyView>
<Label Text="You have no events" VerticalOptions="CenterAndExpand" />
</CollectionView.EmptyView>
<CollectionView.ItemsLayout>
<GridItemsLayout
HorizontalItemSpacing="10"
Orientation="Vertical"
Span="2"
VerticalItemSpacing="10" />
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate>
<Frame
Padding="0"
BackgroundColor="{Binding Color}"
HasShadow="False">
<Frame.Style>
<Style TargetType="Frame">
<!-- To visualy show the selection to the user -->
<Setter Property="VisualStateManager.VisualStateGroups">
<VisualStateGroupList>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal" />
<VisualState x:Name="Selected">
<VisualState.Setters>
<Setter Property="BackgroundColor" Value="CadetBlue" />
<Setter TargetName="uiTime" Property="Label.FontAttributes" Value="Italic" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateGroupList>
</Setter>
</Style>
</Frame.Style>
<StackLayout Padding="10,10,10,0" Spacing="10">
<Label
x:Name="uiTime"
FontAttributes="Bold"
FontSize="Large"
Text="{Binding Time, StringFormat='{0:HH:mm}'}" />
<Label FontSize="15" Text="{Binding Title}" />
<Label
FontSize="Caption"
Text="{Binding Location, StringFormat='At {0}'}"
TextColor="White" />
<StackLayout
Margin="-10,0"
Padding="5"
BackgroundColor="#66000000"
Orientation="Horizontal">
<Image
HeightRequest="20"
HorizontalOptions="EndAndExpand"
Source="ic_edit" />
<Label
FontSize="Caption"
Text="Edit"
TextColor="White"
VerticalOptions="Center" />
</StackLayout>
</StackLayout>
<Frame.GestureRecognizers>
<DragGestureRecognizer DragStartingCommand="{Binding Path=BindingContext.DragStartingCommand, Source={x:Reference EventsCollection}}" DragStartingCommandParameter="{Binding SelectedItems, Source={x:Reference EventsCollection}}" />
</Frame.GestureRecognizers>
</Frame>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
<CollectionView x:Name="EventsCollection2" ItemsSource="{Binding Events2}">
<CollectionView.EmptyView>
<Label Text="You have no events" VerticalOptions="CenterAndExpand" />
</CollectionView.EmptyView>
<CollectionView.ItemsLayout>
<GridItemsLayout
HorizontalItemSpacing="10"
Orientation="Vertical"
Span="2"
VerticalItemSpacing="10" />
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate>
<Frame
Padding="0"
BackgroundColor="{Binding Color}"
HasShadow="False">
<StackLayout Padding="10,10,10,0" Spacing="10">
<Label
x:Name="uiTime2"
FontAttributes="Bold"
FontSize="Large"
Text="{Binding Time, StringFormat='{0:HH:mm}'}" />
<Label FontSize="15" Text="{Binding Title}" />
<Label
FontSize="Caption"
Text="{Binding Location, StringFormat='At {0}'}"
TextColor="White" />
<StackLayout
Margin="-10,0"
Padding="5"
BackgroundColor="#66000000"
Orientation="Horizontal">
<Image
HeightRequest="20"
HorizontalOptions="EndAndExpand"
Source="ic_edit" />
<Label
FontSize="Caption"
Text="Edit"
TextColor="White"
VerticalOptions="Center" />
</StackLayout>
</StackLayout>
<Frame.GestureRecognizers>
<DropGestureRecognizer DropCommand="{Binding BindingContext.DropOverList2Command, Source={x:Reference EventsCollection2}}" />
</Frame.GestureRecognizers>
</Frame>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</StackLayout>
</Frame>
</StackLayout>
</ContentPage.Content>
</ContentPage>
The view model class :
public class EventsPageViewModel
{
private IList<Event> _dragEvent;
/// <summary>
/// It's a Command<IList<object>> beacause of the Selectionmode.Multiple
/// </summary>
public ICommand DragStartingCommand => new Command<IList<object>>((param) =>
{
_dragEvent = new List<Event>(param.Cast<Event>());
});
public ICommand DropOverList2Command => new Command(() =>
{
foreach (var e in _dragEvent)
{
if (Events.Contains(e))
{
Events.Remove(e);
Events2.Add(e);
}
}
});
public ObservableCollection<Event> Events { get; }
public ObservableCollection<Event> Events2 { get; }
public EventsPageViewModel()
{
Events = new ObservableCollection<Event>()
{
{new Event("Go for a walk", "Home", DateTime.Now.AddHours(3), Color.OrangeRed) },
{new Event("Finish PR", "Work", DateTime.Now.AddHours(5), Color.ForestGreen) },
{new Event("Watch a movie", "Home", DateTime.Now.AddMinutes(40), Color.LightSkyBlue) },
};
Events2 = new ObservableCollection<Event>()
{
{new Event("Go for a walk2", "Home", DateTime.Now.AddHours(3), Color.GreenYellow) }
};
}
}
Edit :
I cannot make video but i 've made some screenshots.
Initial state:
Nothing selected, the top collection view is the source, and the bottom collection view is the dest
I select the first item in the top collection view
I select a second item in the top CollectionView
I start dragging by touching and moving the first selected item
the expected result would be something like :
EDIT:
I find something interresting called Windows.UI.Xaml.DragEventArgs.DragUIOverride
see here but apparently it is for uwp, does anybody know if there is an equivalent for Android/iOS ? Thanks for your time
I am using ItemAppearing method pagination in normal listview. but I developed the same code in group listview. But it is a crash. How to use the ItemAppearing method in grouped Listview. Anyone guide me for this scenario. I Paste my code for ur reference.
<ListView x:Name="CustomerListview" ItemAppearing="Handle_ItemAppearing"
IsVisible="true" Footer="" IsGroupingEnabled="true" BackgroundColor="Transparent" Margin="0,10,0,10" SeparatorVisibility="None" HasUnevenRows="True" VerticalOptions="FillAndExpand" HorizontalOptions="CenterAndExpand" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell Height="80">
<StackLayout
Margin="20,0,0,0" Spacing="0" Padding="0"
Orientation="Horizontal"
VerticalOptions="FillAndExpand">
<StackLayout
x:Name="firstStackLayout"
Margin="0,0,0,-6"
HorizontalOptions="Center"
Orientation="Vertical"
VerticalOptions="FillAndExpand">
<BoxView
Grid.Row="0"
Grid.Column="0"
Margin="0,0,0,-6"
HeightRequest="30"
HorizontalOptions="Center"
WidthRequest="2"
VerticalOptions="FillAndExpand"
Color="#b11541" />
<BoxView
Grid.Row="1"
Grid.Column="0"
Margin="0,0,0,0"
HeightRequest="20"
CornerRadius="10"
BackgroundColor="Gray"
WidthRequest="20">
<!--<ff:CachedImage.Transformations>
<ffTransformations:RoundedTransformation
BorderHexColor=""
BorderSize="20"
Radius="240" />
</ff:CachedImage.Transformations>-->
</BoxView>
<BoxView
Grid.Row="2"
Grid.Column="0"
Margin="0,-6,0,0"
HeightRequest="30"
HorizontalOptions="Center"
IsVisible="true"
WidthRequest="2"
VerticalOptions="FillAndExpand"
Color="#b11541" />
</StackLayout>
<StackLayout
Margin="10,15,5,0"
HorizontalOptions="Start"
Orientation="Vertical"
VerticalOptions="Center">
<Label
FontAttributes="Bold"
FontSize="15"
HorizontalOptions="Start"
Text="{Binding Lease_refno}"
TextColor="#b11541"
XAlign="Start" />
<StackLayout
Margin="0,0,5,0"
Orientation="Horizontal"
VerticalOptions="EndAndExpand">
<Label
FontSize="14"
Text="{Binding Billing_start_date}"
TextColor="#4e5156" />
</StackLayout>
</StackLayout>
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Tapped="leaseClicked"/>
</StackLayout.GestureRecognizers>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.GroupHeaderTemplate>
<DataTemplate>
<ViewCell Height="55">
<StackLayout BackgroundColor="Transparent" Padding="5, 5, 5, 0">
<Frame Margin="5,0,5,5" HasShadow="False" IsClippedToBounds="true" BorderColor="Transparent" BackgroundColor="Transparent" CornerRadius="5" Padding="0">
<Grid RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=0.25}"
RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=0.75}"
BackgroundColor="White" ColumnSpacing="0" RowSpacing="0">
<Grid.RowDefinitions>
<RowDefinition Height="5"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="30"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<StackLayout BackgroundColor="White" VerticalOptions="FillAndExpand" Grid.Row="0" Grid.RowSpan="8">
<BoxView HorizontalOptions="Start" WidthRequest="5" BackgroundColor="#b11541" VerticalOptions="FillAndExpand"/>
</StackLayout>
<Label Text="{Binding Customer_company}" TextColor="Black"
FontSize="14" Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="7"
x:Name="originEntry" Margin="20,5,0,5"
VerticalOptions="Start" FontFamily="{StaticResource OpenSansBold}"
HorizontalOptions="FillAndExpand" />
<!--<StackLayout Spacing="0" Grid.Column="0" Padding="0" Margin="0,0,0,10" Grid.Row="2" Orientation="Horizontal">
<Label Text="View Lease" Padding="5,0,5,0" TextColor="White" BackgroundColor="#97304d"
Grid.ColumnSpan="4" FontFamily="{StaticResource OpenSansSemiBold}" Margin="20,0,0,0" FontSize="12"
x:Name="destinationEntry" VerticalOptions="Start"
HorizontalOptions="Start" >
<Label.GestureRecognizers>
<TapGestureRecognizer Tapped="leaseClicked"/>
</Label.GestureRecognizers>
</Label>
</StackLayout>-->
<Grid.GestureRecognizers>
<TapGestureRecognizer NumberOfTapsRequired="1" CommandParameter="{Binding .}" Tapped="HeaderTapped"/>
</Grid.GestureRecognizers>
</Grid>
</Frame>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.GroupHeaderTemplate>
</ListView>
private async void Handle_ItemAppearing(object sender, Xamarin.Forms.ItemVisibilityEventArgs e)
{
var currentIdx = Items.IndexOf((ProductColor)e.Item);
if (currentIdx > _lastItemAppearedIdx)
{
if (Items.Count == 0)
return;
var selectedItem = e.Item as ProductColor;
//hit bottom!
if (isLoading == false && selectedItem == ResultList[ResultList.Count - 1])
{
i++;
await UserTweetsList("lease", "");
}
}
_lastItemAppearedIdx = Items.IndexOf((ProductColor)e.Item);
}
var currentIdx = Items.IndexOf((ProductColor)e.Item
Actually , in the event ItemAppearing you could get the index of current appearing item directly like
int currentIdx = e.ItemIndex ;
And improve the code like :
In group ListView the index with equal -1 when the first item appearing .
if(currentIdx !=-1)
{
// if...
}
In addition , from your code I could not see the part of group . So it could be better to share your sample which contains the issue so that I can test it on my side .
Update
private void CusHandle_ItemAppearing(object sender, Xamarin.Forms.ItemVisibilityEventArgs e)
{
// var currentIdx = customerList.IndexOf((ProductCustomer)e.Item);
int currentIdx = e.ItemIndex;
if (currentIdx != -1)
{
if (currentIdx > _lastItemAppearedIdx)
{
if (_allGroups.Count == 0)
return;
if (currentIdx== _expandedGroups.Count-2)
{
//...
}
_lastItemAppearedIdx = currentIdx;
}
}
}
I'm new to Xamarin.Forms so please excuse me. I'm developing an application using navigation pages,The App main page contains 3 horizontal listviews, Each time I navigate to another page then returns to the main page the app hangs for about a minute recreating all the lists again.
I tried to put the lists creation function on the On-Appearing function but still very slow loading the page
Here's the code for the main page
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:border="clr-namespace:Syncfusion.XForms.Border;assembly=Syncfusion.Core.XForms"
xmlns:listview="clr-namespace:Syncfusion.ListView.XForms;assembly=Syncfusion.SfListView.XForms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:button="clr-namespace:Syncfusion.XForms.Buttons;assembly=Syncfusion.Buttons.XForms"
xmlns:rotator="clr-namespace:Syncfusion.SfRotator.XForms;assembly=Syncfusion.SfRotator.XForms"
xmlns:ListCollection="clr-namespace:System.Collections.Generic;assembly=mscorlib"
xmlns:rating="clr-namespace:Syncfusion.SfRating.XForms;assembly=Syncfusion.SfRating.XForms"
x:Class="GDG6OCT.Views.HomePage"
NavigationPage.HasNavigationBar="False"
FlowDirection="RightToLeft">
<StackLayout>
<ScrollView>
<StackLayout Padding="0">
<rotator:SfRotator x:Name="rotator" HorizontalOptions="FillAndExpand" NavigationDelay="2000" EnableLooping="True"
DotPlacement="None" EnableAutoPlay="true" HeightRequest="160">
<rotator:SfRotator.DataSource>
<ListCollection:List x:TypeArguments="rotator:SfRotatorItem">
<rotator:SfRotatorItem>
<rotator:SfRotatorItem.ItemContent>
<Image Source="slider.png" Margin="0"/>
</rotator:SfRotatorItem.ItemContent>
</rotator:SfRotatorItem>
<rotator:SfRotatorItem>
<rotator:SfRotatorItem.ItemContent>
<Image Source="slider.png" Margin="0"/>
</rotator:SfRotatorItem.ItemContent>
</rotator:SfRotatorItem>
<rotator:SfRotatorItem>
<rotator:SfRotatorItem.ItemContent>
<Image Source="slider.png" Margin="0"/>
</rotator:SfRotatorItem.ItemContent>
</rotator:SfRotatorItem>
</ListCollection:List>
</rotator:SfRotator.DataSource>
</rotator:SfRotator>
<Label Text="جميع الاقسام" HorizontalOptions="StartAndExpand" Margin="20,30,20,0"
Style="{StaticResource MainLabel}"/>
<listview:SfListView x:Name="CatList" Margin="10,0" ItemSize="100"
ItemSpacing="5" Orientation="Horizontal" HeightRequest="100">
<listview:SfListView.ItemTemplate>
<DataTemplate>
<button:SfButton HasShadow="True" BackgroundColor="{Binding BackgroudColor}"
Text="{Binding Name}" HorizontalTextAlignment="Center" VerticalTextAlignment="Center"
FontAttributes="Bold" FontFamily="{StaticResource Second}" Clicked="SfButton_Clicked"
FontSize="11"/>
</DataTemplate>
</listview:SfListView.ItemTemplate>
</listview:SfListView>
<Label Text="أحدث المقررات الدراسية" HorizontalOptions="StartAndExpand" Margin="20,20,20,0"
Style="{StaticResource MainLabel}"/>
<Grid>
<!--<busyindicator:SfBusyIndicator x:Name="busyIndicator1" InputTransparent="True" Grid.Row="0"
AnimationType="Gear "
IsBusy="True"
TextColor="#343694"
ViewBoxWidth="50"
ViewBoxHeight="50" />-->
<listview:SfListView x:Name="CourseList" Margin="10,0" ItemSize="100"
ItemSpacing="4" Orientation="Horizontal" HeightRequest="180">
<listview:SfListView.ItemTemplate>
<!--<DataTemplate>
<Image Source="{Binding CourseImage}">
<Image.GestureRecognizers>
<TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped"/>
</Image.GestureRecognizers>
</Image>
</DataTemplate>-->
<DataTemplate>
<Frame CornerRadius="2"
BorderColor="Transparent"
BackgroundColor="Transparent"
Padding="0">
<StackLayout>
<Frame HasShadow="True" Padding="0" CornerRadius="0" BackgroundColor="Transparent">
<Image Source="{Binding Pro_IMG}" WidthRequest="30" HeightRequest="80" Aspect="AspectFill"/>
</Frame>
<Label Text="{Binding Pro_Name}" FontAttributes="Bold" HorizontalOptions="Start"
FontSize="14" TextColor="Black" FontFamily="{StaticResource Second}"/>
<StackLayout Orientation="Horizontal" HorizontalOptions="Start">
<rating:SfRating x:Name="rating" Value="5" ItemCount="5" ItemSize="10"
ItemSpacing="1" HorizontalOptions="Center"
VerticalOptions="Center">
<rating:SfRating.RatingSettings>
<rating:SfRatingSettings RatedFill="#f4bd01" RatedStrokeWidth="0" UnRatedStrokeWidth="1" />
</rating:SfRating.RatingSettings>
</rating:SfRating>
<Label Text="{Binding Rating, StringFormat='({0})'}" FontFamily="{StaticResource Second}"
VerticalOptions="Center" FontSize="8" HorizontalOptions="Center"/>
</StackLayout>
<StackLayout Orientation="Horizontal">
<Label Grid.Row="3" Grid.ColumnSpan="2" Text="{Binding Pro_Price, StringFormat='{0}EGP'}" TextColor="Gray"
HorizontalOptions="StartAndExpand" FontSize="6" VerticalTextAlignment="Center"
FontFamily="{StaticResource Second}" TextDecorations="Strikethrough"/>
<Label Text="{Binding numberInStock, StringFormat='{0}EGP'}" HorizontalOptions="End" Margin="8,0,0,0" FontFamily="{StaticResource Second}" TextColor="Red"
FontAttributes="Bold" VerticalTextAlignment="Center" FontSize="8"/>
</StackLayout>
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped" />
</StackLayout.GestureRecognizers>
</StackLayout>
</Frame>
</DataTemplate>
</listview:SfListView.ItemTemplate>
</listview:SfListView>
</Grid>
<Label Text="المقررات الدراسية الاشهر" HorizontalOptions="StartAndExpand" Margin="20,20,20,0"
Style="{StaticResource MainLabel}"/>
<Grid>
<!--<busyindicator:SfBusyIndicator x:Name="busyIndicator1" InputTransparent="True" Grid.Row="0"
AnimationType="Gear "
IsBusy="True"
TextColor="#343694"
ViewBoxWidth="50"
ViewBoxHeight="50" />-->
<listview:SfListView x:Name="CourseList1" Margin="10,0" ItemSize="100"
ItemSpacing="4" Orientation="Horizontal" HeightRequest="180">
<listview:SfListView.ItemTemplate>
<DataTemplate>
<Frame CornerRadius="2"
BorderColor="Transparent"
BackgroundColor="Transparent"
Padding="0">
<StackLayout>
<Frame HasShadow="True" Padding="0" CornerRadius="0" BackgroundColor="Transparent">
<Image Source="{Binding Pro_IMG}" WidthRequest="30" HeightRequest="80" Aspect="AspectFill"/>
</Frame>
<Label Text="{Binding Pro_Name}" FontAttributes="Bold" HorizontalOptions="Start"
FontSize="14" TextColor="Black" FontFamily="{StaticResource Second}"/>
<StackLayout Orientation="Horizontal" HorizontalOptions="Start">
<rating:SfRating x:Name="rating" Value="5" ItemCount="5" ItemSize="10"
ItemSpacing="1" HorizontalOptions="Center"
VerticalOptions="Center">
<rating:SfRating.RatingSettings>
<rating:SfRatingSettings RatedFill="#f4bd01" RatedStrokeWidth="0" UnRatedStrokeWidth="1" />
</rating:SfRating.RatingSettings>
</rating:SfRating>
<Label Text="{Binding Rating, StringFormat='({0})'}" FontFamily="{StaticResource Second}"
VerticalOptions="Center" FontSize="8" HorizontalOptions="Center"/>
</StackLayout>
<StackLayout Orientation="Horizontal">
<Label Grid.Row="3" Grid.ColumnSpan="2" Text="{Binding Pro_Price, StringFormat='{0}EGP'}" TextColor="Gray"
HorizontalOptions="StartAndExpand" FontSize="6" VerticalTextAlignment="Center"
FontFamily="{StaticResource Second}" TextDecorations="Strikethrough"/>
<Label Text="{Binding numberInStock, StringFormat='{0}EGP'}" HorizontalOptions="End" Margin="8,0,0,0" FontFamily="{StaticResource Second}" TextColor="Red"
FontAttributes="Bold" VerticalTextAlignment="Center" FontSize="8"/>
</StackLayout>
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped" />
</StackLayout.GestureRecognizers>
</StackLayout>
</Frame>
</DataTemplate>
</listview:SfListView.ItemTemplate>
</listview:SfListView>
</Grid>
<Label Text="المقررات الدراسية المقترحة" HorizontalOptions="StartAndExpand" Margin="20,20,20,0"
Style="{StaticResource MainLabel}"/>
<Grid>
<!--<busyindicator:SfBusyIndicator x:Name="busyIndicator1" InputTransparent="True" Grid.Row="0"
AnimationType="Gear "
IsBusy="True"
TextColor="#343694"
ViewBoxWidth="50"
ViewBoxHeight="50" />-->
<listview:SfListView x:Name="CourseList2" Margin="10,0" ItemSize="100"
ItemSpacing="4" Orientation="Horizontal" HeightRequest="180">
<listview:SfListView.ItemTemplate>
<DataTemplate>
<Frame CornerRadius="2"
BorderColor="Transparent"
BackgroundColor="Transparent"
Padding="0">
<StackLayout>
<Frame HasShadow="True" Padding="0" CornerRadius="0" BackgroundColor="Transparent">
<Image Source="{Binding Pro_IMG}" WidthRequest="30" HeightRequest="80" Aspect="AspectFill"/>
</Frame>
<Label Text="{Binding Pro_Name}" FontAttributes="Bold" HorizontalOptions="Start"
FontSize="14" TextColor="Black" FontFamily="{StaticResource Second}"/>
<StackLayout Orientation="Horizontal" HorizontalOptions="Start">
<rating:SfRating x:Name="rating" Value="5" ItemCount="5" ItemSize="10"
ItemSpacing="1" HorizontalOptions="Center"
VerticalOptions="Center">
<rating:SfRating.RatingSettings>
<rating:SfRatingSettings RatedFill="#f4bd01" RatedStrokeWidth="0" UnRatedStrokeWidth="1" />
</rating:SfRating.RatingSettings>
</rating:SfRating>
<Label Text="{Binding Rating, StringFormat='({0})'}" FontFamily="{StaticResource Second}"
VerticalOptions="Center" FontSize="8" HorizontalOptions="Center"/>
</StackLayout>
<StackLayout Orientation="Horizontal">
<Label Grid.Row="3" Grid.ColumnSpan="2" Text="{Binding Pro_Price, StringFormat='{0}EGP'}" TextColor="Gray"
HorizontalOptions="StartAndExpand" FontSize="6" VerticalTextAlignment="Center"
FontFamily="{StaticResource Second}" TextDecorations="Strikethrough"/>
<Label Text="{Binding numberInStock, StringFormat='{0}EGP'}" HorizontalOptions="End" Margin="8,0,0,0" FontFamily="{StaticResource Second}" TextColor="Red"
FontAttributes="Bold" VerticalTextAlignment="Center" FontSize="8"/>
</StackLayout>
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped" />
</StackLayout.GestureRecognizers>
</StackLayout>
</Frame>
</DataTemplate>
</listview:SfListView.ItemTemplate>
</listview:SfListView>
</Grid>
</StackLayout>
</ScrollView>
<Grid Padding="0" ColumnSpacing="-15" BackgroundColor="{StaticResource DGrey}"
VerticalOptions="EndAndExpand" HorizontalOptions="Fill"
HeightRequest="65" Margin="0" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="65"/>
</Grid.RowDefinitions>
<Button Grid.Column="0" BackgroundColor="#ef3e42" Image="home1.png" TextColor="White"
Text="الرئيسية" ContentLayout="Top,1" FontSize="11" FontFamily="{StaticResource Second}"/>
<Button Grid.Column="1" Clicked="GotoSearchPage" TextColor="White" BackgroundColor="Transparent"
Image="search1.png" FontFamily="{StaticResource Second}"
Text="البحث" ContentLayout="Top, 5" FontSize="10"/>
<Button Grid.Column="2" TextColor="White" BackgroundColor="Transparent"
Image="play.png" FontFamily="{StaticResource Second}" Clicked="GotoMCoursesPage"
Text="كورساتى" ContentLayout="Top, 5" FontSize="10"/>
<Button Grid.Column="3" TextColor="White" BackgroundColor="Transparent" Image="fav2.png" Text="المفضلة" Clicked="GotoFavPage"
FontFamily="{StaticResource Second}" ContentLayout="Top, 5" FontSize="10"/>
<Button Grid.Column="4" TextColor="White" BackgroundColor="Transparent" FontFamily="{StaticResource Second}" Clicked="GotoAccPage"
Image="pers1.png" Text="الحساب" ContentLayout="Top, 5" FontSize="10"/>
</Grid>
</StackLayout>
</ContentPage>
and here is the code for the backend
using GDG6OCT.Models;
using Syncfusion.XForms.Buttons;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace GDG6OCT.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class HomePage : ContentPage
{
public ObservableCollection<Category> Categories = new ObservableCollection<Category>();
public ObservableCollection<Course> Courses = new ObservableCollection<Course>();
public HomePage ()
{
InitializeComponent ();
}
protected override void OnAppearing()
{
creatList();
base.OnAppearing();
}
void creatList()
{
Categories.Add(new Category { Name = "إذاعة", BackgroudColor = Color.Purple });
Categories.Add(new Category { Name = "صحافة إعلام", BackgroudColor = Color.Orange });
Categories.Add(new Category { Name = "نظم معلومات", BackgroudColor = Color.Green });
Categories.Add(new Category { Name = "سياحة وفنادق", BackgroudColor = Color.Pink });
Categories.Add(new Category { Name = "إذاعة ", BackgroudColor = Color.Yellow });
Categories.Add(new Category { Name = "الصحافة والاعلام", BackgroudColor = Color.Red });
Categories.Add(new Category { Name = "نظم معلومات ", BackgroudColor = Color.Purple });
Categories.Add(new Category { Name = "الصحافة", BackgroudColor = Color.Orange });
Categories.Add(new Category { Name = "سياحة وفنادق ", BackgroudColor = Color.Green });
CatList.ItemsSource = Categories;
Courses.Add(new Course { Pro_IMG = "Featured.jpg", Pro_Name = "تقنيات إعلامية", numberInStock = 2000, Pro_Price = "2500", Rating = 13.5f });
Courses.Add(new Course { Pro_IMG = "Featured.jpg", Pro_Name = "علم النفس العام", numberInStock = 2000, Pro_Price = "2500", Rating = 13.5f });
Courses.Add(new Course { Pro_IMG = "Featured.jpg", Pro_Name = "مدخل الى فن الإعلام", numberInStock = 2000, Pro_Price = "2500", Rating = 13.5f });
Courses.Add(new Course { Pro_IMG = "Featured.jpg", Pro_Name = "تقنيات إعلامية", numberInStock = 2000, Pro_Price = "2500", Rating = 13.5f });
Courses.Add(new Course { Pro_IMG = "Featured.jpg", Pro_Name = "علم النفس العام", numberInStock = 2000, Pro_Price = "2500", Rating = 13.5f });
Courses.Add(new Course { Pro_IMG = "Featured.jpg", Pro_Name = "مدخل الى فن الإعلام", numberInStock = 2000, Pro_Price = "2500", Rating = 13.5f });
CourseList.ItemsSource = Courses;
CourseList1.ItemsSource = Courses;
CourseList2.ItemsSource = Courses;
}
private void GotoSearchPage(object sender, EventArgs e)
{
Navigation.PushAsync(new SearchPage());
}
private void GotoMCoursesPage(object sender, EventArgs e)
{
Navigation.PushAsync(new MyCrsPage());
}
private void GotoFavPage(object sender, EventArgs e)
{
Navigation.PushAsync(new FavPage());
}
private void GotoAccPage(object sender, EventArgs e)
{
Navigation.PushAsync(new AccPage());
}
private async void TapGestureRecognizer_Tapped(object sender, EventArgs e)
{
var itemT = (Course)((StackLayout)sender).BindingContext;
CatList.SelectedItem = null;
await Navigation.PushAsync(new CoursePage(itemT));
}
private async void SfButton_Clicked(object sender, EventArgs e)
{
var itemT = (Category)((SfButton)sender).BindingContext;
CatList.SelectedItem = null;
await Navigation.PushAsync(new CategPage(itemT));
}
}
}
UPDATE
I rewrote the listview's dataTemplate using Grid instead of nested stackLayout and cleaned the code a littlebit
<DataTemplate>
<Grid ColumnSpacing="0" RowSpacing="0" Padding="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="2.5*"/>
<RowDefinition Height="1.2*"/>
<RowDefinition Height="0.4*"/>
<RowDefinition Height="0.4*"/>
</Grid.RowDefinitions>
<Frame Grid.Row="0" Grid.ColumnSpan="2" HasShadow="True" Padding="0" BackgroundColor="Transparent">
<Image Source="{Binding Pro_IMG}" Aspect="AspectFill"/>
</Frame>
<Label Grid.Row="1" Grid.ColumnSpan="2" Text="{Binding Pro_Name}" FontAttributes="Bold"
FontSize="14" TextColor="Black" FontFamily="{StaticResource Second}"/>
<rating:SfRating Grid.Row="2" Grid.Column="0" x:Name="rating" Value="5" ItemCount="5" ItemSize="9"
ItemSpacing="1" VerticalOptions="Center">
<rating:SfRating.RatingSettings>
<rating:SfRatingSettings RatedFill="#f4bd01" RatedStrokeWidth="0" UnRatedStrokeWidth="1" />
</rating:SfRating.RatingSettings>
</rating:SfRating>
<Label Grid.Row="2" Grid.Column="1" Text="{Binding Rating, StringFormat='({0})'}" FontFamily="{StaticResource Second}"
FontSize="8" VerticalTextAlignment="Center" HorizontalTextAlignment="Center"/>
<Label Grid.Row="3" Grid.Column="0" Text="{Binding Pro_Price, StringFormat='{0}EGP'}" TextColor="Gray"
HorizontalOptions="StartAndExpand" FontSize="6" VerticalTextAlignment="Center"
FontFamily="{StaticResource Second}" TextDecorations="Strikethrough"/>
<Label Grid.Row="3" Grid.Column="1" Text="{Binding numberInStock, StringFormat='{0}EGP'}" HorizontalOptions="End"
FontFamily="{StaticResource Second}" TextColor="Red" Margin="8,0,0,0"
FontAttributes="Bold" VerticalTextAlignment="Center" FontSize="8"/>
<Grid.GestureRecognizers>
<TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped" />
</Grid.GestureRecognizers>
</Grid>
</DataTemplate>
Do you really need to recreate the Lists again?
If you push a new Page into the stack , then, when popping, you still have your mainpage active, so there is no need to recreate the view.
If you want, you can have a bool indicating if the items were loaded, then, OnAppearing will only load items once.
Example:
private bool _loadedItems=false;
public HomePage ()
{
InitializeComponent ();
}
protected override void OnAppearing()
{
base.OnAppearing();
if(!_loadedItems)
{
creatList();
_loadedItems = true;
}
}
I would strongly suggest reconsidering your layout.
First of all three list views on one single screen isn't the most desirable thing to have in terms of user experience, especially on devices with smaller screens.
If it is possible within your app's requirements I would suggest using a TabbedPage with each ListView being available in it's own tab.
Next thing, sorry to put it that way, but the layout you are using within your ListView cells is a horrible choice in terms of performance. The StackLayout needs a lot more layout cycles in order to determine it's final dimensions, as far as I have seen, you are stacking four of them into a single cell and to make things worse, with one StackLayout containing the other ones.
That takes quite a lot of layout cycles until the xamarin layout engine has finally computed the final size of that ONE(!) view cell and that time gets multiplied by the number of items in your ListView's ItemsSource property.
So what can you do about it? You can quite easily replace your tree of stacklayouts with a single grid (Pro Tip: Do not use "Auto" within the row and column height/width definitions, as this would also take more layout cycles, " * " or " 2* " etc. should do nicely).
Choose the proper amount of columns and rows to display your data and place all your controls, images, labels etc as children of that grid, then use Grid.Row, Grid.Column, Grid.RowSpan and Grid.ColumnSpan for those elements in order put them into the desired position.
This way would save you some layout cycles, so your view should be prepared to display way faster than it is now, especially as the layout cycles reduced by those optimizations also multiply with the amount of your data, but this time in your favor!
i am using xamarin forms with ORM EF i want to show data from product and salesOrderItems in data gridView. my problem that the grid is empty.here my code.
public SalesOrderDetailsVM(int salesOrderItemId)
{
_salesOrderItemId = salesOrderItemId;
_context = new DatabaseContext();
var salesOrderItem = _context.SalesOrderItems.Find(salesOrderItemId);
var idsalesOrder = salesOrderItem.SalesOrderId;
var salesOrder = _context.SalesOrders.Find(idsalesOrder);
var idProd = salesOrderItem.ProductId;
_context = new DatabaseContext();
var Customer = _context.Customers.Where(t => t.CustomerId == salesOrder.CustomerId).FirstOrDefault();
// Setting property values from customer and salesOrder object
// that we get from database
DateCreation = salesOrder.DateCreation;
NumBc = salesOrder.NumBc;
CustomerName = Customer.MangerFullName;
CustomerCIN = Customer.CIN;
var Products = (from p in _context.Products
join o in _context.SalesOrderItems
on p.ProductId equals o.ProductId
select new
{
Code = p.Code,
Designation = p.Designation,
Order_Qty = o.Order_Qty,
PrixUnitaire = p.PrixUnitaire,
TotalHt = o.TotalHt
}).ToList(); }
#Knoop the grid definition
<ListView ItemsSource="{Binding Products}"
SeparatorVisibility="Default"
SelectionMode="None"
>
<ListView.ItemTemplate BackgroundColor="DarkSlateGray" >
<DataTemplate>
<ViewCell>
<Frame Padding="5" BorderColor="DarkSlateGray">
<Grid Padding="5" >
<Grid.ColumnDefinitions BorderColor="DarkSlateGray">
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid BackgroundColor="Transparent" >
<Grid.RowDefinitions BorderColor="DarkSlateGray">
<RowDefinition Height="*" />
</Grid.RowDefinitions>
</Grid>
<Label Text="{Binding Product.Code}" VerticalOptions="Center" Grid.Column="0" />
<Label Text="{Binding Product.Designation}" VerticalOptions="Center" Grid.Column="1" />
<Label Text="{Binding SalesOrderItem.Order_Qty}" VerticalOptions="Center" Grid.Column="2" />
<Label Text="{Binding Product.PrixUnitaire}" VerticalOptions="Center" Grid.Column="3" />
<Label Text="{Binding SalesOrderItem.TotalHt}" VerticalOptions="Center" Grid.Column="4" />
</Grid>
</Frame>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>