Windows phone 8 saving and open links in web Browser history - c#

I have a web browser which is storing all the visited websites. There is just one issue, I would like it for the user to click on one of the records and then it should open in the webbrowser.
Once the user has navigated to a page, this method is called with the url:
public List<String> urls;
public string selectedURL;
public MainPage()
{
InitializeComponent();
listBox.DataContext = urls;
}
private void getHistory(string url)
{
urls.Add(url);
listBox.DataContext = null;
listBox.DataContext = urls;
}
private void listBoxtrend_Tap(object sender, GestureEventArgs e)
{
selectedURL = "";
var selected = listBox.SelectedValue as Item;
selectedText = selected.ItemString;
MessageBox.Show(selectedURL);
browserSearch(selectedURL);
}
This is then displayed into a textblock on a pivot page:
<phone:Pivot Margin="0,0,0,0">
<phone:PivotItem Header="" Margin="0,-104,0,0">
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="72"/>
<RowDefinition Height="696"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0" Background="#FF5E667B" >
</Grid>
</phone:PivotItem>
<phone:PivotItem Margin="0,-104,0,0" Header="">
<Grid>
<ListBox ItemsSource="{Binding Item}" Foreground="RoyalBlue" Name="listBox"
TabIndex="10" Tap="listBox_Tap" >
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock TextWrapping="Wrap" FontSize="26" HorizontalAlignment="Left"
x:Name="txtHistory" Text="{Binding ItemString}"
VerticalAlignment="Top" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</phone:PivotItem>
</phone:Pivot>
I have tried to put a click event, but there is one way to tell which record is being clicked. Is there a way to use the SelectionChanged event handler. And is there a better way to store this data, maybe in a array or list which then can be saved to IsolatedStorage.
Thank you in advance :)
If you need any more details please comment and I will be happy to explain in further detail :)

It's better if you would have the data you're going to display within a Listbox, I mean the Url's. So that you could easily get whatever the data you want from the clicked item. Make sure that you bind the source for your Listbox.
your xaml:
<ListBox ItemsSource="{Binding Item}" Foreground="RoyalBlue"
Height="395" HorizontalAlignment="Center"
Margin="12,111,0,0" Name="listBox"
VerticalAlignment="Top" Width="438"
TabIndex="10" Tap="listBox_Tap" >
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock TextWrapping="Wrap" FontSize="26" HorizontalAlignment="Left"
x:Name="txtHistory" Text="{Binding ItemString}"
VerticalAlignment="Top" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And then from your tap event handler of the Listbox
private async void listBoxtrend_Tap(object sender, GestureEventArgs e)
{
selectedText = "";
var selected = listBox.SelectedValue as Item;
selectedText = selected.ItemString;
MessageBox.Show(selectedText);
await Launcher.LaunchUriAsync(new Uri("give the url"));//here should be the selectedText
}
These can be referable for more:
Getting selected value of listbox windows phone 7
LIstbox Selected Item content to textblock
Hope it helps!

Related

WPF ListBox doesn't show any content

I've got a problem with ListBox. I'm trying to populate it with data from database, but the listbox doesn't show. I've looked through many similar questions, but didn't find any answer that would work for me :(
My code for ListBox:
<ListBox x:Name="OrdersListBox" Grid.Row="1" VerticalContentAlignment="Center" ItemTemplate="{StaticResource OrdersTemplate}">
</ListBox>
And for OrdersTemplate:
<DataTemplate x:Key="OrdersTemplate">
<StackPanel>
<DockPanel DockPanel.Dock="Left" DataContext="{StaticResource OrdersViewSource}">
<TextBlock Text="OrderID: " FontSize="18"/>
<TextBlock Text="{Binding OrderID}" FontSize="18"/>
</DockPanel>
</StackPanel>
</DataTemplate>
Code for Page:
public partial class Account : Page
{
Entities1 Context;
Customers Customer;
CollectionViewSource OrdersViewSource;
public Account(Entities1 Context, Customers Customer)
{
InitializeComponent();
this.Context = Context;
this.Customer = Customer;
this.OrdersViewSource = this.FindResource("OrdersViewSource") as CollectionViewSource;
DataContext = this;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Context.Orders.Load();
this.OrdersViewSource.Source = Context.Orders.Local.Where(o => o.CustomerName == Customer.CompanyName).Select(o => o);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Orders Order = new Orders
{
CustomerName = Customer.CompanyName
};
NewOrder NewOrder = new NewOrder(Context, Order);
this.NavigationService.Navigate(NewOrder);
}
}
I've got also this in Grid.Resources:
<CollectionViewSource x:Key="OrdersViewSource"/>
I'm pretty sure that binding works, 'cause when calling ListBox this way:
<ListBox x:Name="OrdersListBox" Grid.Row="1" VerticalContentAlignment="Center" ItemTemplate="{StaticResource OrdersTemplate}">
<DockPanel/>
</ListBox>
it shows the first OrderID element.
Why can't I see any ListBox when running my app?
Ok what you have done is that you bound your ItemTemplate to the resource you wanted. Which should be ItemsSource instead.
When you added an item manually the list tried to render your item using the template that you provided which is your actual data.
You might want to do something like this:
<ListBox x:Name="OrdersListBox" Grid.Row="1"
VerticalContentAlignment="Center"
ItemTemplate="{StaticResource OrdersTemplate}"
ItemsSource="{Binding Source={StaticResource OrdersViewSource}}">
</ListBox>
And then remove the data binding on the template like this:
<DataTemplate x:Key="OrdersTemplate">
<StackPanel>
<DockPanel DockPanel.Dock="Left">
<TextBlock Text="OrderID: " FontSize="18"/>
<TextBlock Text="{Binding OrderID}" FontSize="18"/>
</DockPanel>
</StackPanel>
</DataTemplate>
I'm not sure of this works because I don't know that if the data in OrdersViewSource is the actual items that you want to show in the list but you get the idea.
You need an array of items assigned to the ItemsSource property of the list.

How to get the destination ListView item on drop?

In UWP C#, I have one ListView in upper row & another in lower row. When I drag a listitem from upper ListView & drop it on lower ListView, I am getting the source. But, I am unable to get the destination. ie) the listview item/(Folder object in my case) where I dropped.
<ListView Name="ListviewCars"
CanDragItems="True" DragItemsStarting="ListviewCars_DragItemsStarting"
SelectionMode="Single" IsItemClickEnabled="True"
DataContext="Cars" ItemsSource="{Binding CarsCollection}">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Background="Transparent" Height="80" Orientation="Horizontal"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate >
<DataTemplate>
<Grid Name="GrdCars" >
<Grid Height="80" Width="90" Padding="5">
<Grid.Background>
<ImageBrush Stretch="Uniform" ImageSource="Assets/car.png"/>
</Grid.Background>
<TextBlock Text="{Binding Name}" FontWeight="Bold" TextWrapping="Wrap" TextAlignment="Center"
HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<ListView Name="GrdViewImg" ScrollViewer.VerticalScrollBarVisibility="Disabled"
AllowDrop="True" DragOver="Image_DragOver"
Drop="Image_OnDrop"
DataContext="Folders" ItemsSource="{Binding FolderCollection}">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Background="Transparent" Height="80" Orientation="Horizontal" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate >
<DataTemplate>
<Grid Name="GrdForFolderMenu" RightTapped="GrdForFolderMenu_RightTapped">
<Grid Height="80" Width="90" Padding="5">
<Grid.Background>
<ImageBrush Stretch="UniformToFill" ImageSource="Assets/Folderimage.png"/>
</Grid.Background>
<TextBlock Text="{Binding Name}" FontWeight="Bold" TextWrapping="Wrap" TextAlignment="Center" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
I have found a simple solution myself. I get the source from DragItemsStarting event of the SoureListView. and target item (as mentioned by ashchuk) from a Grid placed inside Datatemplate of Target ListView. as shown below. Everything works fine now!
(Cars is my Source custom list item. Folders is my Target custom list item)
private void SoureListView_DragItemsStarting(object sender, DragItemsStartingEventArgs e)
{
Cars x = e.Items[0] as Cars;
string DraggedSourceCar = x.Name;
e.Data.Properties.Add("myArgs", DraggedSourceCar);
}
private void GridInsideDatatemplateOfTargetListview_Drop(object sender, DragEventArgs e)
{
var x = sender as Grid;
var y = x.DataContext as Folders;
string toMoveFolderName = y.Name;
string DraggedSourceCar = e.DataView.Properties["myArgs"].ToString();
Debug.WriteLine(DraggedSourceCar + Environment.NewLine + toMoveFolderName );
}
private void TargetListview_DragOver(object sender, DragEventArgs e)
{
e.AcceptedOperation = DataPackageOperation.Copy;
}
You have to find out by yourself = DragEventArgs.GetPosition() in the destination drop, then the underlying item with smoe helper functions
public static object GetObjectAtPoint<ItemContainer>(this ItemsControl control, Point p)
where ItemContainer : DependencyObject
{
// ItemContainer - can be ListViewItem, or TreeViewItem and so on(depends on control)
ItemContainer obj = GetContainerAtPoint<ItemContainer>(control, p);
if (obj == null)
return null;
return control.ItemContainerGenerator.ItemFromContainer(obj);
}
public static ItemContainer GetContainerAtPoint<ItemContainer>(this ItemsControl control, Point p)
where ItemContainer : DependencyObject
{
HitTestResult result = VisualTreeHelper.HitTest(control, p);
if (result != null)
{
DependencyObject obj = result.VisualHit;
while (VisualTreeHelper.GetParent(obj) != null && !(obj is ItemContainer))
{
obj = VisualTreeHelper.GetParent(obj);
}
// Will return null if not found
return obj as ItemContainer;
}
else return null;
}
Did you checked this sample?
After some research I found what DragEventArgs contains an OriginalSource property with Name matches the name of target list when Drop event invoked.
I'm not checked it with folders and subfolders, but maybe OriginalSource will contain folder where item dropped.
<TextBlock Grid.Row="1" Margin="8,4"
VerticalAlignment="Bottom"
Text="All Items"/>
<ListView x:Name="SourceListView"
Grid.Row="2" Margin="8,4"
SelectionMode="Extended"
CanDragItems="True"
DragItemsStarting="SourceListView_DragItemsStarting"/>
<TextBlock Grid.Row="1" Grid.Column="1" Margin="8,4"
VerticalAlignment="Bottom"
Text="Selection"/>
<ListView x:Name="TargetListView"
Grid.Row="2" Grid.Column="1" Margin="8,4"
AllowDrop="True" CanReorderItems="True" CanDragItems="True"
DragOver="TargetListView_DragOver"
Drop="TargetListView_Drop"
DragItemsStarting="TargetListView_DragItemsStarting"
DragItemsCompleted="TargetListView_DragItemsCompleted"/>
And here is printscreen with fired breakpoint:
EDIT:
To get an item inside of TargetList you can do a trick.
I think you use DataTemplate to display custom list items ("folders"). You can see a sample below. As you see I add Grid_DragOver trigger.
<Page.Resources>
<DataTemplate x:Key="ListViewDataTemplate">
<Grid Margin="20,5" DragOver="Grid_DragOver"
BorderBrush="White" BorderThickness="5" AllowDrop="True">
<TextBlock Margin="10" LineHeight="40" FontSize="32" FontWeight="Bold"/>
</Grid>
</DataTemplate>
</Page.Resources>
This way Grid_DragOver will be invoked when mouse pointer enter inside the Grid in DataTemplate.
And if you use binding List<YourFolderClass> as data source, you'll get folder in DataContext. For example I used this:
var SampleData = new ObservableCollection<string>
{
"My Research Paper",
"Electricity Bill",
"My To-do list",
"TV sales receipt",
"Water Bill",
"Grocery List",
"Superbowl schedule",
"World Cup E-ticket"
};
You can see all code in gist.

why are the converters being called again?

In my windows phone app one of the pages contains LongListSelector. In that LongListSelector I am using some converters. When the LongListSelector Loaded the Converters are being called as usual. But when I call ScrollTo() method to scroll to a specific item of the LongListSelector, the converters are being called again. Why are the converters being called again? What does ScrollTo() method do that causes converters to be called again?
Sample Code:
XAML:
<phone:LongListSelector ItemTemplate="{StaticResource LLSItemSource}"
Name="ChatListBox">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<Grid Background="Transparent"
Visibility="{Binding ID, Converter={StaticResource visibilityConverter}}"
Margin="0,6">
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu>
<toolkit:MenuItem Header="delete"
Click="ContextMenuItem_Click" />
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
<Border Background="Black"
HorizontalAlignment="Center"
Padding="30,5,30,8"
CornerRadius="20">
<TextBlock Text="{Binding Date, Converter={StaticResource dateStringConverter}}"
Foreground="White"
FontSize="20" />
</Border>
</Grid>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
CS:
private void ContextMenuItem_Click(object sender, RoutedEventArgs e)
{
string header = (sender as MenuItem).Header.ToString();
MessageModel selectedListBoxItem = (sender as MenuItem).DataContext as MessageModel;
if (selectedListBoxItem == null)
return;
if (header == "delete")
{
DeleteItemByID(selectedListBoxItem.ID);
if (ChatListBox.ItemsSource.Count > 0)
{
ChatListBox.ScrollTo(ChatListBox.ItemsSource[delIndex - 1]); // here I am scrolling to the last item that causes converters to be called again
}
}
}
You are written converter for longlistselector items. On loading every item in selector its get executing to convert value on given template

how to get listbox selected items tag in mainpage xaml

I am developing windows phone 8 app.I need a user response in some part of my application
i create windows phone user control page .User will select a value from a listbox that is in usercontrol page
here is code of my user control page
<Grid x:Name="columngrid" Background="#FF1FCB4E" Width="480" >
<Grid.RowDefinitions>
<RowDefinition Height="300"/>
<RowDefinition Height="70"/>
<RowDefinition Height="70"/>
</Grid.RowDefinitions>
<ListBox Name="URLListBox" Grid.Row="0" Background="#FF1FCB4E" >
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush="#FF0B232F" BorderThickness="2">
<TextBlock x:Name="surename" Width="460" Tag="{Binding b1Tag}" Height="80" FontSize="25" Text="{Binding text}" Foreground="#FFBF9595" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="10,0" />
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button Grid.Row="1" x:Name="btnOK" Content="OK" Background="#FF892121" />
<Button Grid.Row="2" x:Name="btnCancel" Content="Cancel" Background="#FF892121"/>
</Grid>
i want to get selected textblock's text in mainpage.xaml.But When i create class object for user control page i cant reach textblock.I can only reach listbox.How can i get selected textblock's text
I try this but i realized that s will bring listbox object
surah popupsurah = new surah();//usercontrol page
Popup popup2 = new Popup();
private void ApplicationBarIconButton_Click(object sender, EventArgs e)
{
collapsedgrid.Visibility = Visibility.Collapsed;
popupsurah.URLListBox.Tap += (s, args) =>
{
string transferID = ((TextBlock)s).Text as string;
Best way is to do binding with the ListBox SelectedItem property and so you can easily retrieve it from the object itself.
Something like below,(Algorithm)
You can have a class:
class MyClass
{
List<string> Items{get;set;}
string SelectedItem{get;set;}
}
You can pass an instance of this class to the UserControl:
MyUserControl(MyClass);
In the Constructor of MyUserControl:
set the DataContext: this.DataContext=MyClass;
Bind the Property Names in the xaml. Thats it.
Another approach is:
Save the selected Item string into the state dictionary:
PhoneApplicationService.Current.State["SelectedItem"]=YourSelectedItemString;
You can retrieve in the MainPage.xaml like this:
var selectedItem=PhoneApplicationService.Current.State["SelectedItem"] as string;
Better you can go for Phone:LongListSelector control which is more optimised than ListBox,Which has almost all events and properties of ListBox.

accessing an item variable from dynamic data in listbox on SelectionChanged

I am populating a listbox from a webcclient, the data is binded to the listbox and not saved anywhere..
Id like to access binded information when the user selects from the listbox
im having trouble accessing the value of a text block from the SelectionChanged event..
<ListBox x:Name="UsersListBox" ItemsSource="{Binding Items}" Height="471" VerticalAlignment="Top" HorizontalAlignment="Left" Width="457" SelectionChanged="TargetsListBox_SelectionChanged" Grid.ColumnSpan="2">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,17" Width="432" Orientation="Horizontal">
<Image x:Name="ImageAddIcon" Source="blkAdd.png" Height="60" Width="71" VerticalAlignment="Stretch" />
<Image x:Name="ImagePointer" Source="blkClick.png" Height="60" Width="71" VerticalAlignment="Stretch" />
<StackPanel>
<TextBlock Name="txtID" Text="{Binding PlayerID}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" Foreground="#FF8A9A8A" Visibility="Collapsed" />
<TextBlock Name="txtNick" Text="{Binding Nickname}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" Foreground="#FF8A9A8A" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Id like to access the PlayerID from this dynamicly populated list(from webservice) on a onselected basis
private void TargetsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string ID = UsersListBox.SelectedItem ???PlayerID or txtID???;
}
i just want to get the player id that is binded to the listbox with a selection changed event ANY IDEAS!!!!!!!!! <3
Assuming that "Items" is a ObservableCollection:
private void TargetsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var listBox = sender as ListBox;
var selectedItem = listBox.SelectedItem as Player;
if (selectedItem != null)
{
string id = selectedItem.PlayerID
string nick = selectedItem.NickName;
}
}

Categories