An error is occur when i called Web browser.... - windows-phone-7

for (int i = 0; i < list.Count; i++) {
ds = new Discription();
PivotItem pivotItem = new PivotItem();
pivotItem.Header = list.ElementAt(i).header.ToString();
StackPanel sta = new StackPanel();
WebBrowser wb = new WebBrowser();
sta.Children.Add(wb);
pivotItem.Content = sta;
Pivot_item1.Items.Add(pivotItem);
wb.NavigateToString(list.ElementAt(i).Detail.ToString());
}
an error is occur when calling web browser control
You cannot call WebBrowser methods until it is in the visual tree.

Subscribe to the Loaded event of the Webbrowser control and move your navigation code to the loaded handler.
Replace the line
wb.NavigateToString(list.ElementAt(i).Detail.ToString());
with
var address = list.ElementAt(i).Detail.ToString();
wb.Loaded += (sender, e) => { wb.NavigateToString(address); }

for (int i = 0; i < list.Count; i++) {
ds = new Discription();
PivotItem pivotItem = new PivotItem();
pivotItem.Header = list.ElementAt(i).header.ToString();
Grid sta = new Grid();
WebBrowser wb = new WebBrowser();
var address = list.ElementAt(i).Detail.ToString();
wb.Loaded += (sender, e) => { wb.NavigateToString(address); };
sta.Children.Add(wb);
pivotItem.Content = sta;
Pivot_item1.Items.Add(pivotItem);
wb.NavigateToString(list.ElementAt(i).Detail.ToString());
}

Related

Xamarin - binding to variable in datatemplate

How do I bind a value from my object property to a variable so that I can pass it as an argument/parameter for my method "setFavoriteProduct(id_product, favnumber) which is triggered by my button "choiceButton". I require the property value "id_product".
When I bind it to Label "id_productLabel" then I can see it in the View just fine but I need to use the string value in my "setFavoriteProduct" function.
listView.ItemTemplate = new DataTemplate(() =>
{
Image productImage = new Image();
productImage.SetBinding(Image.SourceProperty, "imageURL");
//productImage.HeightRequest = 60;
productImage.HeightRequest = 120;
//productImage.WidthRequest = 60;
productImage.WidthRequest = 120;
productImage.Aspect = Aspect.AspectFit;
Label nameLabel = new Label();
nameLabel.SetBinding(Label.TextProperty, "name");
Label id_productLabel = new Label();
id_productLabel.SetBinding(Label.TextProperty, "id_product");
id_productLabel.IsVisible = true;
Button choiceButton = new Button();
choiceButton.Text = "Vali";
choiceButton.Clicked += (sender, args) => setFavoriteProduct(
id_product,
favnumber
);
return new ViewCell
{
View = new StackLayout
{
Padding = new Thickness(0, 5),
Orientation = StackOrientation.Horizontal,
Children = { productImage, id_productLabel , nameLabel, choiceButton }
}
};
the simplest way to do this is to get the BindingContext from the sender (button) and then get the property from that
choiceButton.Clicked += (sender, args) => {
var context = (MyClass)((Button)sender).BindingContext;
var id = context.id_product;
setFavoriteProduct(id,favnumber);
};
alternately, you could use the Button's Command and CommandParameter properties instead of the Clicked event

How to dynamically create a few pushpin for bing map

How can I dynamically create a few pushpin which I need to add them to the bing Map. Say, I need 10 pushpin.
Below is the code.
for( int i =0 ; i <=10 ; i++)
{
Pushpin pp = new Pushpin();
}
--- Update :
Pushpin[] pp = new Pushpin[intcount];
int PinNbr = 1;
//---- get the items out one by one:
foreach (var c in Cat)
{
if (c.GpsLat != null && c.GpsLon != null)
{
//--default fixed location : Lat/Lon
double KM = CalculateDistance("1.xxxxx", "103.xxxxxx", c.GpsLat, c.GpsLon);
if ((KM < 2.0)) )
{
//--- show the pushpin
pp[PinNbr] = new Pushpin();
pp[PinNbr].Content = c.BizId.ToString() + "," + c.BizName;
pp[PinNbr].Width = 180;
pp[PinNbr].Height = 120;
//-------- All use the same eventHandler
pp[PinNbr].MouseLeftButtonUp += new MouseButtonEventHandler(Pushpin_MouseLeftButtonUp);
map1.Children.Add(pp[PinNbr]);
PinNbr++;
}
}
//-- using Lat/lon
map1.Center = new GeoCoordinate(1.2xxxx, 103.3xxx);
map1.ZoomLevel = 13;
}
//-------- All use the same eventHandler
If you are using BingMaps in Windows Phone 7.1, you can do it like this:
for (int i = 0; i <= 10; i++)
{
Pushpin pp = new Pushpin();
pp.Location = new GeoCoordinate(latitude, longitude);
pp.Content = //Content for the Pushpin;
myMap.Children.Add(pp); //myMap is your map control
}

How to add Dispatcher timer in for loop?

I have to add Dispatcher timer in for loop.I have a multiple pushpin buttons and at run time i wants to retrieve this pushpin buttons in some time interval so how to add dispatcher timer in my loop...
my C# code is....
for (int i = 0; i <= ClsGetDeviceMap.lstLongLatitude.Count - 1; i++)
{
string lat, lon;
lat = ClsGetDeviceMap.lstLatitude.ElementAt<string>(i).Trim();
lon = ClsGetDeviceMap.lstLongLatitude.ElementAt<string>(i).Trim();
Latitude = Convert.ToDouble(lat);
LongLatitude = Convert.ToDouble(lon);
GpsSpeed = 44.21811;
map1.Center = new GeoCoordinate(Latitude, LongLatitude, GpsSpeed);
map1.ZoomLevel = 17;
map1.ZoomBarVisibility = Visibility.Visible;
pin[i] = new Pushpin();
pin[i].Location = new GeoCoordinate(Latitude, LongLatitude);
map1.Children.Add(pin[i]);
myCoorditeWatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
myCoorditeWatcher.MovementThreshold = 20;
//DispatcherTimer newTimer = new DispatcherTimer();
//newTimer.Interval = TimeSpan.FromSeconds(5);
//// newTimer.Tick += map1.Children.Add(pin[i]);
//newTimer.Start();
var gl = GestureService.GetGestureListener(pin[i]);
gl.Hold += new EventHandler<GestureEventArgs>(GestureListener_Hold);
gl.Tap += new EventHandler<GestureEventArgs>(GestureListener_Stack_Tap);
myCoorditeWatcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(myCoorditeWatcher_PositionChanged);
}
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(5000);
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
newTimer.Tick += () =>
{
map1.Children.Add(pin[i]);
// probably you need to stop this timer after one tick
//newTimer.Stop();
};

Problems with deleting items from a listbox

The behaviour Im trying to achieve is to press and hold a listbox item and I should be able to delete the item.
I have created the listbox through code. Everylistitem has a stackpanel which holds two textblocks, ie a date and a string.
How can i get press and hold event for a selectedlistitem?? I have not used binding anywhere.
C#:
for (int i = 0; i < iHistCount; i++)
{
TextBlock dateText = new TextBlock();
TextBlock durationText = new TextBlock();
TextBlock spacer = new TextBlock();
TextBlock spacer2 = new TextBlock();
dateText.FontFamily = (FontFamily)App.Current.Resources["CicleFina"];
durationText.FontFamily = (FontFamily)App.Current.Resources["CicleFina"];
dateText.FontSize = 25;
durationText.FontSize = 25;
dateText.TextAlignment = TextAlignment.Right;
durationText.TextAlignment = TextAlignment.Left;
dateText.VerticalAlignment = System.Windows.VerticalAlignment.Center;
durationText.VerticalAlignment = System.Windows.VerticalAlignment.Center;
spacer.Width = 30;
dateText.Width = 130;
spacer2.Width = 50;
durationText.Width = 170;
DateTime dtHist = pCycMan.GetHistoryDate(i);
strDisplay = dtHist.ToString("dd-MMM-yyyy");
dateText.Text = strDisplay;
if( condition)
{
// logic
durationText.Text = strDisplay;
}
StackPanel st = new StackPanel();
st.Height = 50;
st.Orientation = System.Windows.Controls.Orientation.Horizontal;
st.Children.Add(spacer);
st.Children.Add(dateText);
st.Children.Add(spacer2);
st.Children.Add(durationText);
listboxHistory.Items.Add(st);
}
XAML
<ListBox x:Name="listboxHistory" Height="280" Canvas.Left="60" Canvas.Top="232" Width="360" Foreground="Gray">
Assuming you're using the Silverlight toolkit for a context menu, this link is a good example, and has how to create the menu in code-behind.
http://windowsphonegeek.com/articles/WP7-ContextMenu-in-depth--Part1-key-concepts-and-API
For example here:
StackPanel st = new StackPanel();
st.Height = 50;
st.Orientation = System.Windows.Controls.Orientation.Horizontal;
st.Children.Add(spacer);
st.Children.Add(dateText);
st.Children.Add(spacer2);
st.Children.Add(durationText);
listboxHistory.Items.Add(st);
ContextMenu cm = new ContextMenu();
MenuItem delete = new MenuItem()
{
Header = "Delete",
Tag= "Delete" //you could also put the item itself here, would be a good reference
};
delete.Clicked += //your event handler
MenuItem edit = new MenuItem()
{
Header = "Edit",
Tag = "Edit", //you could also put the item itself here, would be a good reference
};
edit.Clicked += //your event handler
//add the items to the context menu.
cm.Items.Add(delete);
cm.Items.Add(edit);
ContextMenuService.SetContextMenu(st, cm);

Add table to powerpoint slide using Open XML

I got the code for the Table in the powerpoint using the code generator, but I am not able to add the table to an existing powerpoint document.
I tried adding another table to the intended slide and doing the following:
Table table = slidePart.Slide.Descendants<Table>().First();
table.RemoveAllChildren();
Table createdTable = CreateTable();
foreach (OpenXmlElement childElement in createdTable.ChildElements)
{
table.AppendChild(childElement.CloneNode(true));
}
But that didn't work.
I am out of ideas on this issue.
My original target is to add a table with dynamic number of columns and fixed number of row to my presentation.
I know its been very long since this question is posted, but just in case if some one needs a working code to create table in pptx.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Presentation;
using A = DocumentFormat.OpenXml.Drawing;
using System.IO;
namespace ANF.Slides.TestEngine
{
class Program
{
static int index = 1;
static void Main(string[] args)
{
Console.WriteLine("Preparing Presentation");
PopulateData();
// GeneratedClass cls=new GeneratedClass();
//cls.CreatePackage(#"E:\output.pptx");
Console.WriteLine("Completed Presentation");
Console.ReadLine();
}
private static void PopulateData()
{
var overflow = false;
const int pageBorder = 3000000;
var db = new AdventureWorksEntities();
var products = db.Products;//.Take(5);
const string outputFile = #"E:\openxml\output.pptx";
File.Copy(#"E:\OpenXml\Template.pptx", outputFile, true);
using (var myPres = PresentationDocument.Open(outputFile, true))
{
var presPart = myPres.PresentationPart;
var slideIdList = presPart.Presentation.SlideIdList;
var list = slideIdList.ChildElements
.Cast<SlideId>()
.Select(x => presPart.GetPartById(x.RelationshipId))
.Cast<SlidePart>();
var tableSlidePart = (SlidePart)list.Last();
var current = tableSlidePart;
long totalHeight = 0;
foreach (var product in products)
{
if (overflow)
{
var newTablePart = CloneSlidePart(presPart, tableSlidePart);
current = newTablePart;
overflow = false;
totalHeight = 0;
}
var tbl = current.Slide.Descendants<A.Table>().First();
var tr = new A.TableRow();
tr.Height = 200000;
tr.Append(CreateTextCell(product.Name));
tr.Append(CreateTextCell(product.ProductNumber));
tr.Append(CreateTextCell(product.Size));
tr.Append(CreateTextCell(String.Format("{0:00}", product.ListPrice)));
tr.Append(CreateTextCell(product.SellStartDate.ToShortDateString()));
tbl.Append(tr);
totalHeight += tr.Height;
if (totalHeight > pageBorder)
overflow = true;
}
}
}
static SlidePart CloneSlidePart(PresentationPart presentationPart, SlidePart slideTemplate)
{
//Create a new slide part in the presentation
SlidePart newSlidePart = presentationPart.AddNewPart<SlidePart>("newSlide" + index);
index++;
//Add the slide template content into the new slide
newSlidePart.FeedData(slideTemplate.GetStream(FileMode.Open));
//make sure the new slide references the proper slide layout
newSlidePart.AddPart(slideTemplate.SlideLayoutPart);
//Get the list of slide ids
SlideIdList slideIdList = presentationPart.Presentation.SlideIdList;
//Figure out where to add the next slide (find max slide)
uint maxSlideId = 1;
SlideId prevSlideId = null;
foreach (SlideId slideId in slideIdList.ChildElements)
{
if (slideId.Id > maxSlideId)
{
maxSlideId = slideId.Id;
prevSlideId = slideId;
}
}
maxSlideId++;
//Add new slide at the end of the deck
SlideId newSlideId = slideIdList.InsertAfter(new SlideId(), prevSlideId);
//Make sure id and relid is set appropriately
newSlideId.Id = maxSlideId;
newSlideId.RelationshipId = presentationPart.GetIdOfPart(newSlidePart);
return newSlidePart;
}
private static A.TableCell CreateTextCell(string text)
{
var textCol = new string[2];
if (!string.IsNullOrEmpty(text))
{
if (text.Length > 25)
{
textCol[0] = text.Substring(0, 25);
textCol[1] = text.Substring(26);
}
else
{
textCol[0] = text;
}
}
else
{
textCol[0] = string.Empty;
}
A.TableCell tableCell3 = new A.TableCell();
A.TextBody textBody3 = new A.TextBody();
A.BodyProperties bodyProperties3 = new A.BodyProperties();
A.ListStyle listStyle3 = new A.ListStyle();
textBody3.Append(bodyProperties3);
textBody3.Append(listStyle3);
var nonNull = textCol.Where(t => !string.IsNullOrEmpty(t)).ToList();
foreach (var textVal in nonNull)
{
//if (!string.IsNullOrEmpty(textVal))
//{
A.Paragraph paragraph3 = new A.Paragraph();
A.Run run2 = new A.Run();
A.RunProperties runProperties2 = new A.RunProperties() { Language = "en-US", Dirty = false, SmartTagClean = false };
A.Text text2 = new A.Text();
text2.Text = textVal;
run2.Append(runProperties2);
run2.Append(text2);
paragraph3.Append(run2);
textBody3.Append(paragraph3);
//}
}
A.TableCellProperties tableCellProperties3 = new A.TableCellProperties();
tableCell3.Append(textBody3);
tableCell3.Append(tableCellProperties3);
//var tc = new A.TableCell(
// new A.TextBody(
// new A.BodyProperties(),
// new A.Paragraph(
// new A.Run(
// new A.Text(text)))),
// new A.TableCellProperties());
//return tc;
return tableCell3;
}
}
}

Resources