MenuContext not show when holding in WebBrowser Component Windows Phone 8 - c#

When holding in Internet Explorer app, it show a menu context for extra actions(open in new tab, copy link, share link) like this pictures
![Internet Explorer][1]
[1]: http://i.stack.imgur.com/2xNv9.png
But when i add a WebBrowser Component in my Windows Phone 8 project, holding a link but it not show anything. This is xaml code of WebBrowser Component
<phone:WebBrowser Name="webBrowser" IsScriptEnabled="True" Margin="0" Background="Transparent" />
Any one can tell my why and how to fix this?
I tried this but not work
XAML
<phone:WebBrowser Name="webBrowser" IsScriptEnabled="True" Margin="0" Background="Transparent">
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu x:Name="menu1">
<toolkit:MenuItem Header="item1" Click="MenuItem_Click"/>
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
</phone:WebBrowser>
C#
public void AttachContextMenu()
{
try
{
if (webBrowser.IsScriptEnabled)
{
webBrowser.InvokeScript("execScript", "function FindParentLink(item) \r\n{\r\n\tif (!item.parentNode)\r\n\t\treturn null;\r\n\tif (item.tagName.toLowerCase() == 'a') \r\n\t{\r\n\t\treturn item;\r\n\t} \r\n\telse \r\n\t{\r\n\t\treturn FindParentLink(item.parentNode);\r\n\t}\r\n}\r\n\r\nfunction FindParentImage(item) \r\n{\r\n\tif (!item.parentNode)\r\n\t\treturn null;\r\n\tif (item.tagName.toLowerCase() == 'img') \r\n\t{\r\n\t\treturn item;\r\n\t} \r\n\telse \r\n\t{\r\n\t\treturn FindParentImage(item.parentNode);\r\n\t}\r\n}\r\n\r\nfunction HandleContextMenu() \r\n{\r\n\tvar linkItem = FindParentLink(event.srcElement);\r\n var imageItem = FindParentImage(event.srcElement);\r\n var notifyOutput = '';\r\n if (linkItem != null) if (linkItem.href != null) notifyOutput += linkItem.href;\r\n if (imageItem != null) if (imageItem.src != null) notifyOutput += imageItem.src;\r\n if (notifyOutput != '')\r\n window.external.notify(notifyOutput);\r\n else\r\n\t\twindow.external.notify('NOTLINKIMG');\r\n}");
webBrowser.InvokeScript("execScript", "document.oncontextmenu = HandleContextMenu;");
}
}
catch
{
}
}
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
AttachContextMenu();
}

Related

Flyout causing the app to crash [Windows 10] C# XAML

I want the program to show the attached Flyout when user Holding the control (on the mobile) or when the user Right-click the control (on PC).
Here is my XAML :
<DataTemplate x:DataType="data:Cards" x:Key="card">
<StackPanel x:Name="cardstack" Holding="cardstack_Holding" KeyDown="cardstack_KeyDown" >
<StackPanel Background="Blue" Height="100" />
<FlyoutBase.AttachedFlyout>
<MenuFlyout x:Name="optionpass">
<MenuFlyoutItem x:Name="delete" Text="Delete" Click="delete_Click"/>
</MenuFlyout>
</FlyoutBase.AttachedFlyout>
</StackPanel>
</DataTemplate>
and this is my C# :
private void cardstack_Holding(object sender, HoldingRoutedEventArgs e)
{
FlyoutBase.ShowAttachedFlyout(sender as FrameworkElement);
}
private void cardstack_KeyDown(object sender, KeyRoutedEventArgs e)
{
if (e.Key == Windows.System.VirtualKey.RightButton)
{
FlyoutBase.ShowAttachedFlyout(sender as FrameworkElement);
}
}
When I tap and Hold the Stackpanel on the mobile simulator, the Holding event works, but when I Right-click on my PC, it crashes! It says that "There are no attached Flyout!". I do not know what is wrong.
"Have you tried RightTapped event? Is it working?"
Yes and No :(
I just found out the solution to solve my problem.
Turns out you have to name the MenuFlyout like my one is x:Name = "option_menu", and the Flyoutbase.AttachedFlyout cannot be in the DataTemplate, means you have to put it anywhere else except in the DataTemplate, so that the .cs file can find the name of the MenuFlyout.
Here is my C# :
public void cardstack_Holding(object sender, HoldingRoutedEventArgs e)
{
option_menu.ShowAt(sender as FrameworkElement);
e.Handled = true;
}
private void cardstack_PointerPressed(object sender, PointerRoutedEventArgs e)
{
Pointer pointr = e.Pointer;
if (pointr.PointerDeviceType == Windows.Devices.Input.PointerDeviceType.Mouse)
{
Windows.UI.Input.PointerPoint pointrd = e.GetCurrentPoint(sender as UIElement);
if (pointrd.Properties.IsRightButtonPressed)
{
option_menu.ShowAt(sender as FrameworkElement);
}
}
e.Handled = true;
}
Notice that before this I use ShowAttachedFlyout, now I use option_menu.ShowAt.
KeyDown event somehow did not work with my app, so I used PointerPressed instead.
Hope this helps. (0w0)/

Page.BottomAppBar not being refreshed with NavigationCacheMode enabled

Here is my current App flow in a windows phone 8.1:
I have a MainPage with a Pivot and a BottomAppBar
Pivot Item content is populated using the above code in MainPage:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (RootPivot.Items == null) return;
RootPivot_OnPivotItemLoaded(RootPivot, new PivotItemEventArgs { Item = RootPivot.Items[RootPivot.SelectedIndex] as PivotItem });
}
private void RootPivot_OnPivotItemLoaded(Pivot sender, PivotItemEventArgs args)
{
if (args.Item.Content == null) args.Item.Content = CreateUserControlForPivotItem((string)args.Item.Header, sender);
var content = args.Item.Content as UserControl;
if (content == null || content.DataContext == null)
{
BottomAppBar.DataContext = null;
return;
}
BottomAppBar.DataContext = null;
BottomAppBar.DataContext = content.DataContext;
var viewModel = content.DataContext as IRefreshableViewModel;
if (viewModel != null) viewModel.Refresh();
}
private static UserControl CreateUserControlForPivotItem(string pivotItemHeader, Pivot pivot)
{
UserControl item = null;
switch (pivotItemHeader)
{
case "Appointments":
item = new AppointmentsPivotItem();
break;
case "Profile":
item = new ProfilePivotItem();
break;
}
return item;
}
each UserControl has a ViewModel as DataContext, which is responsible of handling the BottomAppBar:
<Page.BottomAppBar>
<CommandBar x:Name="BottomAppBar" Foreground="#FFFEFEFE" Background="{StaticResource BlueColorBrush}" Visibility="{Binding Converter={StaticResource BooleanToVisibilityConverter}, Path=RequiresBottomAppBar, FallbackValue=Collapsed}">
<CommandBar.PrimaryCommands>
<AppBarButton Icon="Add" Label="{Binding AppBarButtonAdd}" Command="{Binding AppBarButtonAddCommand}" Visibility="{Binding Converter={StaticResource BooleanToVisibilityConverter}, Path=RequiresAppBarButtonAdd, FallbackValue=Collapsed}"> </AppBarButton>
<AppBarButton Icon="Find" Label="{Binding AppBarButtonFind}" Command="{Binding AppBarButtonFindCommand}" Visibility="{Binding Converter={StaticResource BooleanToVisibilityConverter}, Path=RequiresAppBarButtonFind, FallbackValue=Collapsed}"></AppBarButton>
</CommandBar.PrimaryCommands>
</CommandBar>
</Page.BottomAppBar>
On the AppointmentsPivotItem I have a ListView and the problem begins when I try to navigate back from an Item details page back to the list.
MainPage has NavigationCacheMode="Enabled" and the binding for the AppBar is being called when navigated back, however, it does not appear until I navigate againg through Pivot items.
Can you please suggest an work around?
Thanks in advance.
Finally, after 1 day I suddenly came to a solution that will do the trick.
Somehow, a call to BottomAppBar.UpdateLayout() before setting its DataContext will force the bar to redraw accordingly to the binding.
Hope this will help someone.

How to use (if possible) same source a tap event uses in a ContextMenu button click?

Im tweaking a Sound Player app to try and include a Save as Ringtone function. App uses Tiles and a Viewmodel. Tapping each tile plays a sound. I added a Context Menu to the Data Template to give the option on a Tap and Hold event to save that sound as a Ringtone. I am having some issues figuring out just how to use the same source as the Tiles use to play the sound. Below, first code is portion of the Mainpage.xaml. Then the c# code. What I have set at the bottom of the MainPage.cs for the _customRingtone Source is wrong. The emulator stops at "SoundData data = selector.SelectedItem as SoundData;" I cant figure out how to do the source in a similar way the Tile taps get the audio for playing it. I didnt post the ViewModel but can if you want me to. That is where the Tile Groups and sounds are loaded.
<phone:PhoneApplicationPage.Resources>
<DataTemplate x:Key="SoundTileDataTemplate">
<StackPanel>
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu>
<toolkit:MenuItem Click="Save_Click" Header="Save as Ringtone" />
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
<Grid Background="{StaticResource PhoneAccentBrush}"
Margin="0, 0, 12, 12">
<Grid VerticalAlignment="Top"
HorizontalAlignment="Right"
Width="40"
Height="40"
Margin="0, 6, 6, 0">
<Ellipse Stroke="{StaticResource PhoneForegroundBrush}"
StrokeThickness="3" />
<Image Source="/Assets/AppBar/Play.png" />
</Grid>
<StackPanel VerticalAlignment="Bottom">
<TextBlock Text="{Binding Title}" Margin="6, 0, 0, 6" />
</StackPanel>
</Grid>
</StackPanel>
</DataTemplate>
</phone:PhoneApplicationPage.Resources>
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<MediaElement
Name="AudioPlayer"
Volume="1" />
<!--Pivot Control-->
<phone:Pivot Title="{Binding Path=LocalizedResources.ApplicationTitle,
Source={StaticResource LocalizedStrings}}">
<phone:PivotItem Header="{Binding Animals.Title}">
<phone:LongListSelector x:Name="Animal"
SelectionChanged="LongListSelector_SelectionChanged"
Margin="0,0,-12,0"
ItemsSource="{Binding Animals.Items}"
LayoutMode="Grid"
GridCellSize="150,150"
ItemTemplate="{StaticResource SoundTileDataTemplate}"
/>
</phone:PivotItem>
public partial class MainPage : PhoneApplicationPage
{
private readonly SaveRingtoneTask
_CustomRingtone;
// Constructor
public MainPage()
{
InitializeComponent();
// Set the data context of the listbox control to the sample data
DataContext = App.ViewModel;
_CustomRingtone = new SaveRingtoneTask();
_CustomRingtone.Completed +=
customeRingtone_Completed;
BuildLocalizedApplicationBar();
}
// Load data for the ViewModel Items
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (!App.ViewModel.IsDataLoaded)
{
App.ViewModel.LoadData();
}
}
private void LongListSelector_SelectionChanged(object sender,
SelectionChangedEventArgs e)
{
LongListSelector selector = sender as LongListSelector;
// verifying our sender is actually a LongListSelector
if (selector == null)
return;
SoundData data = selector.SelectedItem as SoundData;
// verifying our sender is actually SoundData
if (data == null)
return;
private void customeRingtone_Completed(object sender, TaskEventArgs e)
{
if (e.TaskResult == TaskResult.OK)
{
MessageBox.Show(#"Saved");
}
else if (e.TaskResult == TaskResult.Cancel)
{
MessageBox.Show(#"Canceled");
}
else
{
MessageBox.Show(#"Not Saved");
}
}
private void Save_Click(object sender, System.Windows.RoutedEventArgs e)
{
LongListSelector selector = sender as LongListSelector;
SoundData data = selector.SelectedItem as SoundData;
**_CustomRingtone.Source = new Uri(data.FilePath, UriKind.RelativeOrAbsolute**);
_CustomRingtone.DisplayName = "Ring";
_CustomRingtone.Show();
}
You Save_Click event handler is not passed a LLS, but a context MenuItem. The DataContext of the MenuItem is the object you are after.
private void Save_Click(object sender, System.Windows.RoutedEventArgs e)
{
var element = (FrameworkElement)sender;
SoundData data = element.DataContext as SoundData;
_CustomRingtone.Source = new Uri(data.FilePath, UriKind.RelativeOrAbsolute**);
_CustomRingtone.DisplayName = "Ring";
_CustomRingtone.Show();
}

Delete task is not working under Context Menu?

I was developing Windows Phone App using this sample: Local Database Sample
In that sample, Delete Task has been implemented using an icon. I have modified Delete Task by Context Menu. But, it does not works for me.
If I pressed Delete, nothing happens.
I dunno what mistake I have done.
My modified Code:
XAML Code:
<TextBlock
Text="{Binding ItemName}"
FontWeight="Thin" FontSize="28"
Grid.Column="0" Grid.Row="0"
VerticalAlignment="Top">
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu Name="ContextMenu">
<toolkit:MenuItem Name="Delete" Header="Delete" Click="deleteTaskButton_Click"/>
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
</TextBlock>
C# Code:
private void deleteTaskButton_Click(object sender, RoutedEventArgs e)
{
// Cast the parameter as a button.
var button = sender as TextBlock;
if (button != null)
{
// Get a handle for the to-do item bound to the button.
ToDoItem toDoForDelete = button.DataContext as ToDoItem;
App.ViewModel.DeleteToDoItem(toDoForDelete);
MessageBox.Show("Deleted Successfully");
}
// Put the focus back to the main page.
this.Focus();
}
Working original Code in that sample:
XAML Code:
<TextBlock
Text="{Binding ItemName}"
FontSize="{StaticResource PhoneFontSizeLarge}"
Grid.Column="1" Grid.ColumnSpan="2"
VerticalAlignment="Top" Margin="-36, 12, 0, 0"/>
<Button
Grid.Column="3"
x:Name="deleteTaskButton"
BorderThickness="0"
Margin="0, -18, 0, 0"
Click="deleteTaskButton_Click">
<Image
Source="/Images/appbar.delete.rest.png"
Height="75"
Width="75"/>
</Button>
C# Code:
private void deleteTaskButton_Click(object sender, RoutedEventArgs e)
{
// Cast the parameter as a button.
var button = sender as Button;
if (button != null)
{
// Get a handle for the to-do item bound to the button.
ToDoItem toDoForDelete = button.DataContext as ToDoItem;
App.ViewModel.DeleteToDoItem(toDoForDelete);
MessageBox.Show("Deleted Successfully");
}
// Put the focus back to the main page.
this.Focus();
}
In your case sender is not a TextBlock, so this line:
var button = sender as TextBlock;
returns null
You can cast it to MenuItem.
using Microsoft.Phone.Controls;
....
private void deleteTaskButton_Click(object sender, RoutedEventArgs e)
{
var item = sender as MenuItem;
if (item!= null)
{
// Get a handle for the to-do item bound to the button.
ToDoItem toDoForDelete = item .DataContext as ToDoItem;
App.ViewModel.DeleteToDoItem(toDoForDelete);
MessageBox.Show("Deleted Successfully");
}
// Put the focus back to the main page.
this.Focus();
}

Use WindowsFormHost inside a wpf tooltip

i am trying to host a windows form panel inside a ToolTip.
Below is the Xaml code and the class behind for the ToolTip.
The issue is if I'm using windowsFormsHost the panel doesnt change the color, it feels like the ToolTip doesn't even know it's there.
Am I doing it right?
(If I'm able to change the color then I will use it to show a liveFeed of a camera)
When I click on the button, the ToolTip is there but it stays basic.
If I have no Windows Form Host and use a StackPanel then it works.
But I need to use the Panel.
Xaml :
<Grid>
<Button Width="100" Height="100">
<Button.ToolTip>
<Controls:MyToolTip Height="500" Width="550">
<WindowsFormsHost x:Name="wrapper" Margin="0,0,0,0" Background="{x:Null}">
<wf:Panel x:Name="previewScreen" BackColor="Purple" Size="200,200" >
</wf:Panel>
</WindowsFormsHost>
</Controls:MyToolTip>
</Button.ToolTip>
</Button>
</Grid>
C# :
public class MyToolTip : ToolTip
{
protected override void OnTemplateChanged(ControlTemplate oldTemplate, ControlTemplate newTemplate)
{
if (newTemplate != null)
{
this.Visibility = Visibility.Collapsed;
this.IsOpen = true;
Popup popup = GetPopupFromVisualChild(this);
if (popup != null) popup.AllowsTransparency = false;
this.IsOpen = false;
this.Visibility = Visibility.Visible;
}
}
private static Popup GetPopupFromVisualChild(Visual child)
{
Visual parent = child;
FrameworkElement visualRoot = null;
while (parent != null)
{
visualRoot = parent as FrameworkElement;
parent = VisualTreeHelper.GetParent(parent) as Visual;
}
Popup popup = null;
if (visualRoot != null)
{
popup = visualRoot.Parent as Popup;
}
return popup;
}
}
Thanks for your time and help.
The problem is that the panel has no content, so It doesn't show the background.
Try this:
<Grid>
<Button Width="100" Height="100">
<Button.ToolTip>
<Controls:MyToolTip >
<WindowsFormsHost x:Name="wrapper" Margin="0,0,0,0" Background="{x:Null}" >
<wf:Panel x:Name="previewScreen" BackColor="Purple" Size="200,200" >
<wf:Panel.Controls>
<wf:Label Text="Test"></wf:Label>
</wf:Panel.Controls>
</wf:Panel>
</WindowsFormsHost>
</Controls:MyToolTip>
</Button.ToolTip>
</Button>
</Grid>

Categories

Resources