I am trying to display user's facebook profile picture. I have a working FacebookRenderer in my android project. I just need some guidelines on how to display the actual image. Below is my attempt on what I've tried but picture does not display. Any help will be appreciated.
I basically created a renderer for the Facebook Login in my android project and user details are saved and passed to the PCL using the Settings plugin(allowing my user's info to be saved in static variable)
FacebookRenderer:
public class FacebookRender : PageRenderer
{
public FacebookRender()
{
String error;
var activity = this.Context as Activity;
var auth = new OAuth2Authenticator(
clientId: "",
scope: "email",
authorizeUrl: new Uri("https://www.facebook.com/dialog/oauth/"),
redirectUrl: new Uri("https://www.facebook.com/connect/login_success.html")
);
auth.Completed += async (sender, eventArgs) =>
{
try
{
if (eventArgs.IsAuthenticated)
{
await AccountStore.Create().SaveAsync(eventArgs.Account, "FacebookProviderKey");
var accessToken = eventArgs.Account.Properties["access_token"].ToString();
var expiresIn = Convert.ToDouble(eventArgs.Account.Properties["expires_in"]);
var expiryDate = DateTime.Now + TimeSpan.FromSeconds(expiresIn);
var request = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me?fields=email,first_name,last_name,gender,picture"), null, eventArgs.Account);
var response = await request.GetResponseAsync();
var obj = JObject.Parse(response.GetResponseText());
var id = obj["id"].ToString().Replace("\"", "");
var name = obj["first_name"].ToString().Replace("\"", "");
var surname = obj["last_name"].ToString().Replace("\"", "");
var gender = obj["gender"].ToString().Replace("\"", "");
var email = obj["email"].ToString().Replace("\"", "");
var profilePic = obj["picture"].ToString().Replace("\"", "");
Customer.Customers cust = new Customer.Customers();
cust.Number = "";
cust.Name = name;
cust.Surname = surname;
cust.Address = " ";
cust.Email = email;
cust.City = " ";
cust.Region = " ";
cust.Country = " ";
cust.MobilePhone = " ";
cust.DOB = DateTime.Now;
cust.Phone = " ";
cust.Credentials = new Customer.Credentials();
cust.Credentials.Authenticated = true;
cust.Credentials.SecretKey = "73fnfdbjfdj";
cust.DeviceToken = GcmService.RegistrationID;
Helpers.Settings.picture = profilePic;
CustomerService service = new CustomerService();
Settings.Token = await service.AddCustomer(cust);
Helpers.Settings.Usertoken = Settings.Token;
if (Helpers.Settings.MobileNo == null || Helpers.Settings.MobileNo == " ")
{
await App.NavigateToSMS();
}
else
{
App.NavigateToVerified();
}
}
else
{
App.NavigateToProfile();
}
}
catch(Exception ex)
{
error = ex.Message;
}
};
activity.StartActivity(auth.GetUI(activity));
}
Xaml
<StackLayout Orientation="Horizontal" HorizontalOptions="Center" VerticalOptions="CenterAndExpand">
<StackLayout Orientation="Vertical" HorizontalOptions="Center">
<Image x:Name="profilePic" HeightRequest="30" WidthRequest="30"/>
</StackLayout>
<StackLayout Orientation="Vertical" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand">
<Label x:Name="lblMessage" FontSize="Medium" HorizontalOptions="Center" TextColor="White" VerticalOptions="CenterAndExpand" />
</StackLayout>
</StackLayout>
Xaml.cs
profilePic.Source = Helpers.Settings.picture;
I am creating a UI using a grid in Xamarin which I have put in StackLayout.
Below is the following code for xaml.
program.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="LoginPage.Page">
<ContentPage.Content>
<StackLayout Orientation="Vertical">
<StackLayout BackgroundColor="#3a4851">
<Label Text="Identifications" TextColor="White" FontSize="15" Margin="10" />
</StackLayout>
<StackLayout>
<Grid x:Name="identificationGridLayout" HorizontalOptions="Center"></Grid>
</StackLayout>
<StackLayout BackgroundColor="#3a4851">
<Label Text="Deciles" TextColor="White" FontSize="15" Margin="10" />
</StackLayout>
<StackLayout>
<Grid x:Name="decileGridLayout" HorizontalOptions="Center"></Grid>
</StackLayout>
</StackLayout>
</ContentPage.Content>
</ContentPage>
I am creating the Grid header and data programatically.
program.cs
public partial class Page : ContentPage
{
private LoadingPopUp popUp;
private Repository repository = new Repository();
private JObject jResult;
private List<string> rowHeader;
private List<PrescriberIdentitifcation> prescriberIdentificationValue;
private List<PrescriberDecile> prescriberDecileValue;
public Page() { InitializeComponent(); }
public Page(string guid)
{
InitializeComponent();
FetchDataForDetail(guid);
}
async void FetchDataForDetail(string guid)
{
try
{
popUp = new LoadingPopUp("Loading data ...");
await PopupNavigation.PushAsync(popUp);
//Get Identification Data for prescriber
JObject identificationResult = await GetRepositoryDetailData(guid);
var identificationdata = JsonConvert.DeserializeObject<PrescriberIdentificationList>(identificationResult.ToString());
prescriberIdentificationValue = identificationdata.value;
int index = 0;
foreach (var obj in identificationResult["value"])
{
prescriberIdentificationValue[index].vcm_type_name = (string)obj["vcm_type#OData.Community.Display.V1.FormattedValue"];
index++;
}
drawIdentificationGrid();
//Get Deciles Data for prescriber
JObject decileResult = await GetRepositoryDetailData(guid);
var deciledata = JsonConvert.DeserializeObject<PrescriberIdentificationList>(decileResult.ToString());
prescriberIdentificationValue = deciledata.value;
Debug.WriteLine("data prescriberIdentificationValue : " + prescriberIdentificationValue);
drawDecilesGrid();
await PopupNavigation.PopAllAsync();
}
catch (Exception ex) {
Debug.WriteLine("error in identification loading : " + ex.Message);
await PopupNavigation.PopAllAsync();
}
}
public async Task<JObject> GetRepositoryDetailData(string guid, string entity, string filter)
{
try
{
jResult = await repository.Retrieve(GlobalVariables.AuthToken, entity, filter + guid);
return jResult;
}
catch (Exception err)
{
Debug.WriteLine(err.Message);
await PopupNavigation.PopAllAsync();
await DisplayAlert("Error", "Oops something went wrong", "Ok");
}
return jResult;
}
void drawIdentificationGrid()
{
try
{
rowHeader = new List<string>{"Type", "Number", "License State", "Sampleability","Expiration Date","License Status" };
drawGridHeader(identificationGridLayout,1, rowHeader.Count,rowHeader);
for (int rowIndex = 1; rowIndex <= prescriberIdentificationValue.Count; rowIndex++)
{
var datatypeLabel = new Label { Text = prescriberIdentificationValue[rowIndex-1].vcm_type_name.ToString(),FontSize=12, VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center };
var datanumberLabel = new Label { Text = prescriberIdentificationValue[rowIndex-1].vcm_name.ToString(),FontSize=12, VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center };
var datalicenseStateLabel = new Label { Text = (prescriberIdentificationValue[rowIndex-1]._vcm_licensestate_value != null) ? prescriberIdentificationValue[rowIndex-1]._vcm_licensestate_value : "-" , FontSize=12, VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center };
var datasampleabiltiyLabel = new Label { Text = (prescriberIdentificationValue[rowIndex - 1].vcm_sampleability == false) ? "No": "Yes", FontSize=12, VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center };
var dataexpirationDateLabel = new Label { Text = (prescriberIdentificationValue[rowIndex-1].vcm_expirationdate != null) ? prescriberIdentificationValue[rowIndex-1].vcm_expirationdate : "-", FontSize=12, VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center };
Debug.WriteLine("data datatypeLabel {0} datanumberLabel {1} datalicenseStateLabel {2} datasampleabiltiyLabel {3} dataexpirationDateLabel {4} rowIndex {5}",datatypeLabel.Text,datanumberLabel.Text,datalicenseStateLabel.Text, datasampleabiltiyLabel.Text, dataexpirationDateLabel.Text, rowIndex);
identificationGridLayout.Children.Add(datatypeLabel, 0, rowIndex);
identificationGridLayout.Children.Add(datanumberLabel, 1, rowIndex);
identificationGridLayout.Children.Add(datalicenseStateLabel, 2, rowIndex);
identificationGridLayout.Children.Add(datasampleabiltiyLabel, 3, rowIndex);
identificationGridLayout.Children.Add(dataexpirationDateLabel, 4, rowIndex);
}
}
catch (Exception ex) { Debug.WriteLine("Error in drawing Identifications: "+ ex.Message);}
}
void drawDecilesGrid()
{
try
{
rowHeader = new List<string>{"Quarter", "Decile Type", "Decile", "Rank","Organization Type" };
drawGridHeader(decileGridLayout,1, rowHeader.Count, rowHeader);
//for (int rowIndex = 1; rowIndex <= prescriberIdentificationValue.Count; rowIndex++)
//{
// var datatypeLabel = new Label { Text = prescriberIdentificationValue[rowIndex - 1].vcm_type_name.ToString(), FontSize = 12, VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center };
// var datanumberLabel = new Label { Text = prescriberIdentificationValue[rowIndex - 1].vcm_name.ToString(), FontSize = 12, VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center };
// var datalicenseStateLabel = new Label { Text = (prescriberIdentificationValue[rowIndex - 1]._vcm_licensestate_value != null) ? prescriberIdentificationValue[rowIndex - 1]._vcm_licensestate_value : "-", FontSize = 12, VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center };
// var datasampleabiltiyLabel = new Label { Text = (prescriberIdentificationValue[rowIndex - 1].vcm_sampleability == false) ? "No" : "Yes", FontSize = 12, VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center };
// var dataexpirationDateLabel = new Label { Text = (prescriberIdentificationValue[rowIndex - 1].vcm_expirationdate != null) ? prescriberIdentificationValue[rowIndex - 1].vcm_expirationdate : "-", FontSize = 12, VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center };
// Debug.WriteLine("data datatypeLabel {0} datanumberLabel {1} datalicenseStateLabel {2} datasampleabiltiyLabel {3} dataexpirationDateLabel {4} rowIndex {5}",datatypeLabel.Text,datanumberLabel.Text,datalicenseStateLabel.Text, datasampleabiltiyLabel.Text, dataexpirationDateLabel.Text, rowIndex);
// identificationGridLayout.Children.Add(datatypeLabel, 0, rowIndex);
// identificationGridLayout.Children.Add(datanumberLabel, 1, rowIndex);
// identificationGridLayout.Children.Add(datalicenseStateLabel, 2, rowIndex);
// identificationGridLayout.Children.Add(datasampleabiltiyLabel, 3, rowIndex);
// identificationGridLayout.Children.Add(dataexpirationDateLabel, 4, rowIndex);
//}
}
catch (Exception ex) { Debug.WriteLine("Error in drawing Identifications: "+ ex.Message);}
}
void drawGridHeader(Grid gridLayout, int rowIndexLength, int columnIndexLength, List<string> rowHeaders)
{
try
{
gridLayout.RowDefinitions = new RowDefinitionCollection();
gridLayout.ColumnDefinitions = new ColumnDefinitionCollection();
for (int rowIndex = 0; rowIndex < rowIndexLength; rowIndex++)
{
gridLayout.RowDefinitions.Add(new RowDefinition());
}
for (int columnIndex = 0; columnIndex <= columnIndexLength; columnIndex++)
{
gridLayout.ColumnDefinitions.Add(new ColumnDefinition());
}
for (int i = 0; i < columnIndexLength; i++)
{
var label = new Label { Text = rowHeaders[i], FontSize = 14, VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center };
identificationGridLayout.Children.Add(label, i, 0);
}
}
catch (Exception ex) { Debug.WriteLine("Error in drawing grid header: "+ ex.Message);}
}
}
}
drawGridHeader() is common to creating Header for different grids. Data for the cell is passed in different functions and grid reference is passed to it.
Ex: -
rowHeader = new List<string>{"Quarter", "Decile Type", "Decile", "Rank","Organization Type" };
drawGridHeader(decileGridLayout,1, rowHeader.Count, rowHeader);
But after fetching the data, The Grid is over writing on each other.
I tried creating manual grid with row item and they are stacking properly in order but when programmatically doing it, grid is stacking upon each other.
It should been below the Label Decile.
Inside the last for-loop in drawGridHeader(), you're not referencing the passed in grid when adding the labels:
for (int i = 0; i < columnIndexLength; i++)
{
var label = new Label { Text = rowHeaders[i], FontSize = 14, VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center };
// This references the wrong Grid
// identificationGridLayout.Children.Add(label, i, 0);
gridLayout.Children.Add(label, i, 0);
}
I have a RichTextBlock in a ListViewItem in a ListView. I can't for the life of me findout why the text wrapping on the RichTextBlock won't apply.
XAML:
<ScrollViewer x:Name="MessagesScroller" HorizontalScrollMode="Disabled">
<ListView x:Name="Messages" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch"/>
</ScrollViewer>
C#
ListViewItem listviewitem = new ListViewItem();
listviewitem.HorizontalContentAlignment = HorizontalAlignment.Stretch;
listviewitem.VerticalAlignment = VerticalAlignment.Stretch;
listviewitem.Tag = message.Id;
StackPanel stack = new StackPanel();
stack.Orientation = Orientation.Horizontal;
stack.VerticalAlignment = VerticalAlignment.Stretch;
Image Avatar = new Image();
Avatar.Height = 50;
Avatar.VerticalAlignment = VerticalAlignment.Top;
Avatar.Source = new BitmapImage(new Uri("https://cdn.discordapp.com/avatars/" + message.User.Id + "/" + message.User.Avatar + ".jpg"));
stack.Children.Add(Avatar);
StackPanel innerstack = new StackPanel();
innerstack.VerticalAlignment = VerticalAlignment.Stretch;
StackPanel MsgData = new StackPanel();
MsgData.Orientation = Orientation.Horizontal;
#region RichTextBlock
RichTextBlock user = new RichTextBlock();
user.TextWrapping = TextWrapping.WrapWholeWords;
Paragraph userPara = new Paragraph();
Run run1 = new Run();
run1.Text = message.User.Username;
userPara.Inlines.Add(run1);
user.Blocks.Add(userPara);
#endregion
MsgData.Children.Add(user);
#region RichTextBlock
RichTextBlock timestamp = new RichTextBlock();
Paragraph timePara = new Paragraph();
Run run2 = new Run();
run2.Text = message.Timestamp.Month.ToString() + "/" + message.Timestamp.Day + " at " + message.Timestamp.Hour.ToString() + ":";
if (message.Timestamp.Minute < 9)
{
run2.Text += "0";
}
run2.Text += message.Timestamp.Minute.ToString();
timestamp.Foreground = GetSolidColorBrush("#FF333333");
timePara.Inlines.Add(run2);
timestamp.Blocks.Add(timePara);
timestamp.Margin = new Thickness(5, 0, 0, 0);
#endregion
MsgData.Children.Add(timestamp);
innerstack.Children.Add(MsgData);
#region RichTextBlock
RichTextBlock txtblock = new RichTextBlock();
txtblock.TextWrapping = TextWrapping.WrapWholeWords;
Paragraph txtPara = new Paragraph();
Run run3 = new Run();
run3.Text = message.Content;
txtPara.Inlines.Add(run3);
txtblock.Blocks.Add(txtPara);
foreach (SharedModels.Embed embed in message.Embeds)
{
Paragraph paragraph = new Paragraph();
if (embed.title != null)
{
Run title = new Run();
title.Text = embed.title + "\n";
paragraph.Inlines.Add(title);
}
if (embed.Description != null)
{
Run desc = new Run();
desc.Text = embed.Description + "\n";
paragraph.Inlines.Add(desc);
}
if (embed.Thumbnail.Url != null)
{
InlineUIContainer container = new InlineUIContainer();
BitmapImage bi = new BitmapImage(new Uri(embed.Thumbnail.ProxyUrl));
Image image = new Image();
image.Height = 300;
image.Source = bi;
container.Child = image;
paragraph.Inlines.Add(container);
}
txtblock.Blocks.Add(paragraph);
}
foreach (SharedModels.Attachment attach in message.Attachments)
{
Paragraph paragraph = new Paragraph();
Run run = new Run();
run.Text = attach.Filename;
BitmapImage bi = new BitmapImage(new Uri(attach.Url));
Image image = new Image();
image.Height = 300;
image.Source = bi;
InlineUIContainer container = new InlineUIContainer();
container.Child = image;
paragraph.Inlines.Add(run);
paragraph.Inlines.Add(container);
txtblock.Blocks.Add(paragraph);
}
#endregion
innerstack.Children.Add(txtblock);
stack.Children.Add(innerstack);
listviewitem.Content = stack;
#region Flyout
Flyout flyout = new Flyout();
StackPanel flyoutcontent = new StackPanel();
flyoutcontent.Margin = new Thickness(-10);
/*Button AddRection = new Button()
{
Content = "Add Reaction",
HorizontalAlignment = HorizontalAlignment.Stretch
};
flyoutcontent.Children.Add(AddRection);
Button Pin = new Button()
{
Content = "Pin",
HorizontalAlignment = HorizontalAlignment.Stretch
};
flyoutcontent.Children.Add(Pin);*/
/*Button Edit = new Button()
{
Content = "Edit",
HorizontalAlignment = HorizontalAlignment.Stretch,
Tag = message.Id
};
Edit.Click += EditMessage;
flyoutcontent.Children.Add(Edit);*/
Button Delete = new Button()
{
Content = "Delete",
HorizontalAlignment = HorizontalAlignment.Stretch,
Tag = message.Id
};
Delete.Click += DeleteThisMessage;
flyoutcontent.Children.Add(Delete);
flyout.Content = flyoutcontent;
listviewitem.ContextFlyout = flyout;
listviewitem.RightTapped += OpenRightTapFlyout;
listviewitem.Holding += OpenHoldingFlyout;
#endregion
Messages.Items.Add(listviewitem);
I have uprooted my entire program to use StackPanels instead but that didn't help
You used StackPanel for your layout and set the Orientation property to Horizontal for the StackPanel. StackPanel is size to its children. So it seems like the reason is that you don't set the Width property for the RichTextBlock. The width of RichTextBlock size to its content, StackPanelsize toRichTextBlock`, it may not wrap.
You may have several ways to resolve this:
Set width property for the RichTextBlock.
RichTextBlock txtblock = new RichTextBlock();
txtblock.Width = 300;
txtblock.TextWrapping = TextWrapping.WrapWholeWords;
Remove the orientation property for the StackPanel if you don't need such a layout.
//stack.Orientation = Orientation.Horizontal;
Or you may use a Grid instead. Grid may better help you define the layout. You may define the image and RichTextBlock layout as followings.
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Image Source="Assets/caffe1.jpg" Height="100" Grid.Row="0" Grid.Column="0"></Image>
<RichTextBlock TextWrapping="WrapWholeWords" Grid.Row="0" Grid.Column="1">
<Paragraph>
<Run FontStyle="Italic">sample text todemonstrate some properties.demonstrate some properties.demonstrate some properties.demonstrate some properties.
demonstrate some properties.demonstrate some properties.demonstrate some properties.demonstrate some properties.demonstrate some properties.
</Run>
</Paragraph>
</RichTextBlock>
</Grid>
I was trying to make daily calendar and I create this:
xaml:
<Page
x:Class="Calendar.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Calendar"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid>
<Pivot x:Name="CalendarPivot" Title="Pivot" SelectionChanged="CalendarPivot_SelectionChanged">
</Pivot>
</Grid>
<Page.BottomAppBar>
<CommandBar>
<AppBarButton x:Name="TodayAppBarButton" Label="dziś" Click="TodayAppBarButton_Click">
<AppBarButton.Icon>
<FontIcon x:Name="TodayFontIcon" Glyph="" FontSize="10" FontFamily="Segoe WP"/>
</AppBarButton.Icon>
</AppBarButton>
<AppBarButton x:Name="ChooseDateAppBarButton" Label="wybierz" Icon="Calendar" Click="ChooseDateAppBarButton_Click">
<FlyoutBase.AttachedFlyout>
<DatePickerFlyout DatePicked="DatePickerFlyout_DatePicked"/>
</FlyoutBase.AttachedFlyout>
</AppBarButton>
</CommandBar>
</Page.BottomAppBar>
c#:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Navigation;
namespace Calendar
{
public sealed partial class MainPage : Page
{
bool pivotClear = false;
public MainPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var monthDatefmt = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("month.abbreviated");
SetCalendar(DateTimeOffset.Now);
TodayFontIcon.Glyph = DateTimeOffset.Now.Day + " " + monthDatefmt.Format(DateTimeOffset.Now);
}
private void SetCalendar(DateTimeOffset startDate)
{
var loader = new Windows.ApplicationModel.Resources.ResourceLoader();
var dayOfWeekDatefmt = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("dayofweek.full");
var dayMonthYearDatefmt = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("day month year");
for (int i = -4; i < 5; i++)
{
PivotItem pivotItem = new PivotItem();
DateTimeOffset date = new DateTimeOffset();
date = startDate.AddDays(i);
pivotItem.Tag = date.Month + "/" + date.Day + "/" + date.Year;
if (date.Date == DateTimeOffset.Now.Date)
{
pivotItem.Header = loader.GetString("Today");
}
else
{
pivotItem.Header = dayOfWeekDatefmt.Format(date).ToLower();
}
CalendarPivot.Items.Add(pivotItem);
}
CalendarPivot.SelectedIndex = 4;
CalendarPivot.Title = dayMonthYearDatefmt.Format(startDate).ToUpper();
}
private void CalendarPivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var loader = new Windows.ApplicationModel.Resources.ResourceLoader();
Debug.WriteLine("change started" + CalendarPivot.SelectedIndex);
if (!pivotClear)
{
var sdatefmt = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("dayofweek.full");
var dayMonthYearDatefmt = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("day month year");
PivotItem selectedPivotItem = CalendarPivot.SelectedItem as PivotItem;
DateTimeOffset selectedPivotItemDate = new DateTimeOffset();
selectedPivotItemDate = DateTimeOffset.Parse(selectedPivotItem.Tag as string);
CalendarPivot.Title = dayMonthYearDatefmt.Format(selectedPivotItemDate).ToUpper();
PivotItem lastPivotItem = CalendarPivot.Items.Last() as PivotItem;
DateTimeOffset lastPivotItemDate = new DateTimeOffset();
lastPivotItemDate = DateTimeOffset.Parse(lastPivotItem.Tag as string);
if (selectedPivotItemDate.Date >= lastPivotItemDate.Date.AddDays(-3))
{
PivotItem pivotItem = new PivotItem();
DateTimeOffset date = new DateTimeOffset();
date = lastPivotItemDate.AddDays(1);
pivotItem.Tag = date.Month + "/" + date.Day + "/" + date.Year;
if (date.Date == DateTimeOffset.Now.Date)
{
pivotItem.Header = loader.GetString("Today");
}
else
{
pivotItem.Header = sdatefmt.Format(date).ToLower();
}
CalendarPivot.Items.Add(pivotItem);
}
PivotItem firstPivotItem = CalendarPivot.Items.First() as PivotItem;
DateTimeOffset firstPivotItemDate = new DateTimeOffset();
firstPivotItemDate = DateTimeOffset.Parse(firstPivotItem.Tag as string);
if (selectedPivotItemDate.Date <= firstPivotItemDate.Date.AddDays(3))
{
PivotItem pivotItem = new PivotItem();
DateTimeOffset date = new DateTimeOffset();
date = firstPivotItemDate.AddDays(-1);
pivotItem.Tag = date.Month + "/" + date.Day + "/" + date.Year;
if (date.Date == DateTimeOffset.Now.Date)
{
pivotItem.Header = "dziś";
}
else
{
pivotItem.Header = sdatefmt.Format(date).ToLower();
}
CalendarPivot.Items.Insert(0, pivotItem);
}
}
Debug.WriteLine("change ended" + CalendarPivot.SelectedIndex);
}
private void TodayAppBarButton_Click(object sender, RoutedEventArgs e)
{
pivotClear = true;
CalendarPivot.Items.Clear();
SetCalendar(DateTimeOffset.Now);
pivotClear = false;
}
private void ChooseDateAppBarButton_Click(object sender, RoutedEventArgs e)
{
FlyoutBase.ShowAttachedFlyout((FrameworkElement)sender);
}
private void DatePickerFlyout_DatePicked(DatePickerFlyout sender, DatePickedEventArgs args)
{
pivotClear = true;
DateTimeOffset date = args.NewDate;
CalendarPivot.Items.Clear();
SetCalendar(date);
pivotClear = false;
}
}
}
It works well when I change days forward, but I have one heavyweight bug in backward way. I will try to explain it in steps.
Today is monday and user changes it to previous day.
Pivot's selected item changes from 4(monday) to 3(sunday) .
System decects that it must generate one more item to pivot.
System generates new item and inserts it in 0 position.
Pivot's selected item changes from 3 to 4(now sunday).
Pivot still shows item 3 which is saturday now, and it's looks like calendar skipped one day.
I would be very grateful if someone knows how to fix it.
EDIT :
I made change based on Nate Diamond suggestion and it works for now well:
Here, have a code:
XAML:
<Page
x:Class="LetsMakeANewCalendar.NewCalendar"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:LetsMakeANewCalendar"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid>
<Pivot x:Name="CalendarPivot" Title="" SelectionChanged="CalendarPivot_SelectionChanged">
<PivotItem x:Name="PivotItem0"/>
<PivotItem x:Name="PivotItem1"/>
<PivotItem x:Name="PivotItem2"/>
<PivotItem x:Name="PivotItem3"/>
<PivotItem x:Name="PivotItem4"/>
<PivotItem x:Name="PivotItem5"/>
<PivotItem x:Name="PivotItem6"/>
</Pivot>
</Grid>
<Page.BottomAppBar>
<CommandBar>
<AppBarButton x:Name="TodayAppBarButton" Label="dziś" Click="TodayAppBarButton_Click">
<AppBarButton.Icon>
<FontIcon x:Name="TodayFontIcon" Glyph="" FontSize="10" FontFamily="Segoe WP"/>
</AppBarButton.Icon>
</AppBarButton>
<AppBarButton x:Name="ChooseDateAppBarButton" Label="wybierz" Icon="Calendar" Click="ChooseDateAppBarButton_Click">
<FlyoutBase.AttachedFlyout>
<DatePickerFlyout DatePicked="DatePickerFlyout_DatePicked"/>
</FlyoutBase.AttachedFlyout>
</AppBarButton>
</CommandBar>
</Page.BottomAppBar>
C#:
public sealed partial class NewCalendar : Page
{
int pivotIndex;
DateTimeOffset previousDate = new DateTimeOffset();
public NewCalendar()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var monthDatefmt = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("month.abbreviated");
SetCalendar(DateTimeOffset.Now);
TodayFontIcon.Glyph = DateTimeOffset.Now.Day + " " + monthDatefmt.Format(DateTimeOffset.Now);
}
private void SetCalendar(DateTimeOffset startDate)
{
var loader = new Windows.ApplicationModel.Resources.ResourceLoader();
var dayOfWeekDatefmt = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("dayofweek.full");
var dayMonthYearDatefmt = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("day month year");
int numberOfDay = GetNumberOfDay(startDate);
int i = 0;
foreach (PivotItem item in CalendarPivot.Items)
{
DateTimeOffset date = new DateTimeOffset();
date = startDate.AddDays(i - numberOfDay);
item.Tag = date.Month + "/" + date.Day + "/" + date.Year;
item.Header = dayOfWeekDatefmt.Format(date).ToLower();
i++;
}
CalendarPivot.SelectedIndex = pivotIndex = numberOfDay;
}
private int GetNumberOfDay(DateTimeOffset date)
{
int numberOfDay;
switch (date.DayOfWeek)
{
case DayOfWeek.Monday:
numberOfDay = 0;
break;
case DayOfWeek.Tuesday:
numberOfDay = 1;
break;
case DayOfWeek.Wednesday:
numberOfDay = 2;
break;
case DayOfWeek.Thursday:
numberOfDay = 3;
break;
case DayOfWeek.Friday:
numberOfDay = 4;
break;
case DayOfWeek.Saturday:
numberOfDay = 5;
break;
case DayOfWeek.Sunday:
numberOfDay = 6;
break;
default:
numberOfDay = -1;
break;
}
return numberOfDay;
}
private void CalendarPivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var loader = new Windows.ApplicationModel.Resources.ResourceLoader();
Debug.WriteLine("old pivot index " + pivotIndex);
Debug.WriteLine("change started " + CalendarPivot.SelectedIndex);
var dayMonthYearDatefmt = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("day month year");
if ((CalendarPivot.SelectedIndex == 6) && (pivotIndex == 0))
{
SetCalendar(previousDate.AddDays(-1));
}
else if ((CalendarPivot.SelectedIndex == 0) && (pivotIndex == 6))
{
SetCalendar(previousDate.AddDays(1));
}
PivotItem selectedPivotItem = CalendarPivot.SelectedItem as PivotItem;
DateTimeOffset selectedPivotItemDate = new DateTimeOffset();
selectedPivotItemDate = DateTimeOffset.Parse(selectedPivotItem.Tag as string);
previousDate = selectedPivotItemDate.Date;
pivotIndex = CalendarPivot.SelectedIndex;
CalendarPivot.Title = dayMonthYearDatefmt.Format(selectedPivotItemDate).ToUpper();
if (selectedPivotItemDate.Date == DateTimeOffset.Now.Date)
{
CalendarPivot.Title += " - " + loader.GetString("Today").ToUpper();
}
Debug.WriteLine("change ended " + CalendarPivot.SelectedIndex);
Debug.WriteLine("new pivot index " + pivotIndex);
}
private void TodayAppBarButton_Click(object sender, RoutedEventArgs e)
{
var loader = new Windows.ApplicationModel.Resources.ResourceLoader();
var dayMonthYearDatefmt = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("day month year");
SetCalendar(DateTimeOffset.Now);
PivotItem selectedPivotItem = CalendarPivot.SelectedItem as PivotItem;
DateTimeOffset selectedPivotItemDate = new DateTimeOffset();
selectedPivotItemDate = DateTimeOffset.Parse(selectedPivotItem.Tag as string);
previousDate = selectedPivotItemDate.Date;
pivotIndex = CalendarPivot.SelectedIndex;
CalendarPivot.Title = dayMonthYearDatefmt.Format(selectedPivotItemDate).ToUpper() + " - " + loader.GetString("Today").ToUpper();
}
private void ChooseDateAppBarButton_Click(object sender, RoutedEventArgs e)
{
FlyoutBase.ShowAttachedFlyout((FrameworkElement)sender);
}
private void DatePickerFlyout_DatePicked(DatePickerFlyout sender, DatePickedEventArgs args)
{
var loader = new Windows.ApplicationModel.Resources.ResourceLoader();
var dayMonthYearDatefmt = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("day month year");
DateTimeOffset date = args.NewDate;
SetCalendar(date);
PivotItem selectedPivotItem = CalendarPivot.SelectedItem as PivotItem;
DateTimeOffset selectedPivotItemDate = new DateTimeOffset();
selectedPivotItemDate = DateTimeOffset.Parse(selectedPivotItem.Tag as string);
previousDate = selectedPivotItemDate.Date;
pivotIndex = CalendarPivot.SelectedIndex;
CalendarPivot.Title = dayMonthYearDatefmt.Format(selectedPivotItemDate).ToUpper();
if (selectedPivotItemDate.Date == DateTimeOffset.Now.Date)
{
CalendarPivot.Title += " - " + loader.GetString("Today").ToUpper();
}
}
}
I am trying to generate dynamic controls in grid through UI where am dynamically specifying the size of controls. while generating more then 1500 control it is throwing this error "Not enough quota is available to process this command. (Exception from HRESULT: 0x80070718) " . i have seen some solution for gridview for the same exception but i am using GRID so not beneficial for me .
please let me know.
Thanks in advance.
<ScrollViewer HorizontalScrollMode="Auto"
HorizontalScrollBarVisibility="Auto"
VerticalScrollMode="Auto"
VerticalScrollBarVisibility="Auto" Margin="232,10,267,0" Grid.Row="1">
<Grid Name="dynamicgrid" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="LightBlue" Height="Auto" Width="Auto" Grid.Row="1"/>
</ScrollViewer>
C# code
try
{
MainPage mainpage = (MainPage)e.Parameter;
buttons = Convert.ToInt32(mainpage.buttonsize);
textblock = Convert.ToInt32(mainpage.txtBlocksize);
textbox = Convert.ToInt32(mainpage.txtBoxsize);
rows = Convert.ToInt32(mainpage.rows);
buttonwidth = Convert.ToInt32(mainpage.buttonwidth);
textblockwidth = Convert.ToInt32(mainpage.txtBlockwidth);
textboxwidth = Convert.ToInt32(mainpage.txtBoxwidth);
grdcolumn = buttons + textblock + textbox;
for (int i = 0; i < rows; i++)
{
RowDefinition rowDef = new RowDefinition();
rowDef.Height = new GridLength(200, GridUnitType.Auto);
dynamicgrid.RowDefinitions.Add(rowDef);
}
for (int j = 0; j < grdcolumn; j++) //need to mention
{
ColumnDefinition colDef1 = new ColumnDefinition();
colDef1.Width = new GridLength(100, GridUnitType.Auto);
dynamicgrid.ColumnDefinitions.Add(colDef1);
}
for (textboxcolumncount = 0; textboxcolumncount < textbox; textboxcolumncount++)
{
for (int i = 0; i < rows; i++)//textbox
{
TextBox txtbox = new TextBox();
txtbox.SetValue(TextBox.TextProperty, "txtbox" + i.ToString());
txtbox.Width = textboxwidth;
txtbox.Height = 50;
txtbox.SetValue(Grid.ColumnProperty, textboxcolumncount);
txtbox.SetValue(Grid.RowProperty, i);
dynamicgrid.Children.Add(txtbox);
dynamicgrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
}
}
textboxcolumncount = textbox;
for (textblockcolumncount = textboxcolumncount; textblockcolumncount < (grdcolumn - (buttons)); textblockcolumncount++)
{
for (int i = 0; i < rows; i++)
{
TextBlock txtblock = new TextBlock();
txtblock.SetValue(TextBlock.NameProperty, "txtblock" + i.ToString());
txtblock.Width = textblockwidth;
txtblock.Height = 50;
txtblock.SetValue(Grid.ColumnProperty, textblockcolumncount);
txtblock.SetValue(Grid.RowProperty, i);
txtblock.Text = "TextBlock" + i.ToString();
txtblock.Foreground = new SolidColorBrush(Colors.Black);
dynamicgrid.Children.Add(txtblock);
dynamicgrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
}
}
textboxcolumncount = textblockcolumncount;
for (buttonCoulmncount = textboxcolumncount; buttonCoulmncount < (grdcolumn); buttonCoulmncount++)
{
for (int i = 0; i < rows; i++) //button
{
Button btn = new Button();
btn.SetValue(Button.NameProperty, "btn" + i.ToString());
btn.Content = "Button" + i.ToString();
btn.Width = textboxwidth;
btn.Height = 50;
btn.Foreground = new SolidColorBrush(Colors.Black);
btn.SetValue(Grid.RowProperty, i);
btn.SetValue(Grid.ColumnProperty, buttonCoulmncount);
dynamicgrid.Children.Add(btn);
dynamicgrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
}
}
}
catch (Exception ex)
{
throw ex;
}
Go through this Link I am not sure wether this will solve your problem or you will have an idea of it.
Not enough quota ex
After that you can make a search. I still have not found any issue like this. Guess have to Replicate the code on the system. :)