how to convert WebView into IRandomAccessStream in UWP? - xaml

What i have Tried is?
My Xaml code :
<Grid x:Name="MyGrid">
<Button x:Name="but" Content="Click" Click="but_Click"></Button>
</Grid>
My C# code:
private async void but_Click(object sender, RoutedEventArgs e)
{
WebView x = new WebView();
x.Width = 100; x.Height = 100;
InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream();
await x.CapturePreviewToStreamAsync(ms);
}
when I try to convert Webview to Stream.It throws an error like this.
I don't why this was happening .Can Anyone suggest me , How to convert webview to IRandomAccessstream?

The problem is the WebView has not rendered into xaml visual tree. we need to insert WebView into Page content before calling CapturePreviewToStreamAsync method.
private WebView x;
public MainPage()
{
this.InitializeComponent();
x = new WebView();
x.Height = 100; x.Width = 100;
RootGrid.Children.Add(x);
}
private async void bookmarkBtn_Click(object sender, RoutedEventArgs e)
{
InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream();
await x.CapturePreviewToStreamAsync(ms);
}

Related

UWP hangs when loading Rich Text document as embedded resource

I'm trying to include some rich text with my app, but the app hangs when trying to load the text.
// Here is the initiating call:
await aboutDialog.ShowAsync();
// This code hangs on the second line
private async void Page_Loaded(object sender, RoutedEventArgs e)
{
var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("XamlSandbox.cities.rtf");
myRichEditBox.Document.LoadFromStream(Windows.UI.Text.TextSetOptions.FormatRtf, stream.AsRandomAccessStream());
}
// This code works OK
private async void Page_Loaded(object sender, RoutedEventArgs e)
{
var picker = new Windows.Storage.Pickers.FileOpenPicker();
var file = await picker.PickSingleFileAsync();
var fileStream = await file.OpenAsync(FileAccessMode.Read);
myRichEditBox.Document.LoadFromStream(Windows.UI.Text.TextSetOptions.FormatRtf, fileStream);
}
I've tried loading the embedded resource into a memory stream and using that, but that hangs too. Any ideas?
Here is how to properly load the embedded resource in UWP:
var rtfUri = new Uri("ms-appx:///cities.rtf");
var file = await StorageFile.GetFileFromApplicationUriAsync(rtfUri);
var stream = file.OpenAsync(FileAccessMode.Read);
myRichEditBox.Document.LoadFromStream(Windows.UI.Text.TextSetOptions.FormatRtf, stream.GetResults());

Trying to stop SpeechSynthesizer in uwp on click of a button

I'm trying to stop SpeechSynthesizer in uwp on click of a button and also trying to start SpeechSynthesizer on clicking same icon again.Any Help would be appreciated for resolution of this issue.
XAML
<Image x:Name="Sound" Source="ABCD/sound_active.png"
RelativePanel.AlignBottomWithPanel="True"
RelativePanel.RightOf="Pause" Tapped="SoundTap"
Margin="17,0,0,0"
Width="40" Height="40"/>
C# code
private void SoundTap(object sender, TappedRoutedEventArgs e)
{
if ((Sound.Source as BitmapImage).UriSource == new Uri("ms-appx:///ABCD/Sound_active.png", UriKind.Absolute))
{
Sound.Source = new BitmapImage(new Uri("ms-appx:///ABCD/Sound_mute.png"));
textToSpeech.Stop();
}
else
{
Sound.Source = new BitmapImage(new Uri("ms-appx:///ABCD/Sound_active.png"));
textToSpeech.Play();
}
}
public async void Prevevent(object sender, TappedRoutedEventArgs e)
{
currentIndex--;
if (currentIndex < 0)
{
currentIndex = 0;
return;
}
Alph_cap.Source = new BitmapImage(new Uri("ms-appx:///ABCD/Cap_alpha/Cap_" + currentIndex + ".png"));
Alph_small.Source = new BitmapImage(new Uri("ms-appx:///ABCD/Cap_alpha/Sml_" + currentIndex + ".png"));
CapAlphaName.Text = CapsAlpha[currentIndex];
SmallAlphaName.Text = SmallAlpha[currentIndex];
var speechText = this.CapAlphaName.Text;
if (speechText != "")
{
var synth = new SpeechSynthesizer();
var speechStream =await synth.SynthesizeTextToStreamAsync(speechText);
this.textToSpeech.AutoPlay = true;
this.textToSpeech.SetSource(speechStream, speechStream.ContentType);
this.textToSpeech.Play();
}
}
Understanding the question:
Basically you're looking for a toggle switch to turn on and turn off the speech synthesis tts(Text to Speech) in simpler terms.
The Solution:
This couldn't have been simpler enough, never the less, this is how you do it.
Create a Bool property, eg: private IsTTSEnabled = false we'll use this as a flag.
On your Image tap or click, check the current value of IsTTSEnabled and flip it (false if true or true if false) eg: IsTTSEnable = !IsTTSEnable;
Now put a if loop for handling if the TTS is turned on or if it's turned off. Also, since TTS is done using a media element, you don't need to reInitialize your TTS, simple pause and play your media element or start and Stop it as per needs.
So your c# code becomes:
private bool IsTTSEnabled = false;
private void SoundTap(object sender, TappedRoutedEventArgs e)
{
IsTTSEnabled = !IsTTSEnabled;
if(IsTTSEnabled)
{
Sound.Source = new BitmapImage(new Uri("ms-appx:///ABCD/Sound_mute.png"));
textToSpeech.Stop();
}
else
{
Sound.Source = new BitmapImage(new Uri("ms-appx:///ABCD/Sound_active.png"));
textToSpeech.Play();
}
}
Note: This functionality can be easily implemented using Data Binding to provide scalability and ease of management but then the simpler way to do so is like the one I've illustrated

Custom CommandBar to PickerFlyout

By default PickerFlyout has commandbar that has done and cancel buttons. Is it possible to disable done button programmatically? If not is there any way to add custom command bar and replace default one?
With the help of the answer given i tried to write custom picker from PickerFlyoutBase. But now i'm not able to add content to flyout in xaml. Giving me error saying custompicker doesnt support direct content
<Button>
<Button.Flyout>
<local:custompicker>
<TextBlock Margin="20" FontSize="30" Text="MyPickerFlyout Test" />
</local:custompicker>
</Button.Flyout>
</Button
public class custompicker:PickerFlyoutBase
{
private AppBar OriginalAppBar;
private CommandBar MyCommandBar;
private Page CurrentPage;
public custompicker()
{
var cancelButton = new AppBarButton();
cancelButton.Icon = new SymbolIcon(Symbol.Cancel);
cancelButton.Label = "Cancel";
cancelButton.Click += (s, e) =>
{
this.Hide();
};
MyCommandBar = new CommandBar();
MyCommandBar.PrimaryCommands.Add(cancelButton);
this.Closed += MyPickerFlyout_Closed;
this.Opening += MyPickerFlyout_Opening;
this.Placement = Windows.UI.Xaml.Controls.Primitives.FlyoutPlacementMode.Full;
}
private void MyPickerFlyout_Opening(object sender, object e)
{
CurrentPage = (Windows.UI.Xaml.Window.Current.Content as Frame).Content as Page;
if (CurrentPage != null)
{
OriginalAppBar = CurrentPage.BottomAppBar;
CurrentPage.BottomAppBar = MyCommandBar;
}
}
private void MyPickerFlyout_Closed(object sender, object e)
{
if (CurrentPage != null)
{
CurrentPage.BottomAppBar = OriginalAppBar;
}
}
}
PickerFlyout class has a ConfirmationButtonsVisible property, we can use this property to disable both "Done" and "Cancel" button.
But there is no way to disable only "Done" button. We have to implement a custom "PickerFlyout". Following is a simple custom "PickerFlyout" based on Flyout, you can refer to it to implement your own.
public class MyPickerFlyout : Flyout
{
private AppBar OriginalAppBar;
private CommandBar MyCommandBar;
private Page CurrentPage;
public MyPickerFlyout()
{
var cancelButton = new AppBarButton();
cancelButton.Icon = new SymbolIcon(Symbol.Cancel);
cancelButton.Label = "Cancel";
cancelButton.Click += (s, e) =>
{
this.Hide();
};
MyCommandBar = new CommandBar();
MyCommandBar.PrimaryCommands.Add(cancelButton);
this.Closed += MyPickerFlyout_Closed;
this.Opening += MyPickerFlyout_Opening;
this.Placement = Windows.UI.Xaml.Controls.Primitives.FlyoutPlacementMode.Full;
}
private void MyPickerFlyout_Opening(object sender, object e)
{
CurrentPage = (Windows.UI.Xaml.Window.Current.Content as Frame)?.Content as Page;
if (CurrentPage != null)
{
OriginalAppBar = CurrentPage.BottomAppBar;
CurrentPage.BottomAppBar = MyCommandBar;
}
}
private void MyPickerFlyout_Closed(object sender, object e)
{
if (CurrentPage != null)
{
CurrentPage.BottomAppBar = OriginalAppBar;
}
}
}
Then you can use it in XAML like:
<Button Content="Show Picker">
<Button.Flyout>
<local:MyPickerFlyout Closed="PickerFlyout_Closed">
<TextBlock Margin="20" FontSize="30" Text="MyPickerFlyout Test" />
</local:MyPickerFlyout>
</Button.Flyout>
</Button>
And it looks like:

Create Application bar dynamically

I want to create Application Bar dynamically in Windows Phone 8. I have used the following code to create application bar in appbar.cs file
class AppBar
{
public AppBar()
{
ApplicationBar appbar;
this.appbar = new ApplicationBar();
this.appbar.IsVisible = true;
this.appbar.Opacity = 1;
this.appbar.Mode = ApplicationBarMode.Minimized;
ApplicationBarIconButton appButon = new ApplicationBarIconButton();
appButon.IconUri = new Uri("/images/show.png", UriKind.Relative);
appButon.Text = "Show";
this.appbar.Buttons.Add(appButon);
appButon.Click += appButon_Click;
}
}
void appButon_Click(object sender, EventArgs e)
{
}
}
If i have created the instance of AppBar class, then all the methods called but i unable to see the application bar. I have given request to create the appbar from webview. From the javainterface i have created the instance of application bar with the given text and icon. How to show this in the web page.
I have solved the my Application bar issue. Added my application bar with parent element(PhoneApplicationPage).
class AppBar
{
public AppBar()
{
ApplicationBar appbar;
PhoneApplicationPage parentpage = (Application.Current.RootVisual as ContentControl).Content as PhoneApplicationPage;
parentpage.ApplicationBar = new ApplicationBar();
appbar = parentpage.ApplicationBar;
appbar.IsVisible = true;
appbar.Opacity = 1;
appbar.Mode = ApplicationBarMode.Minimized;
ApplicationBarIconButton appButon = new ApplicationBarIconButton();
appButon.IconUri = new Uri("/images/show.png", UriKind.Relative);
appButon.Text = "Show";
appbar.Buttons.Add(appButon);
appButon.Click += appButon_Click;
}
}
void appButon_Click(object sender, EventArgs e)
{
}
}

How to open any specific SettingsFlyout in WinRT app

I am working on a Windows 8 metro app and having multiple SettingsFlyout items which get added by below mentioned code
SettingsCommand cmd1 = new SettingsCommand("sample", "Color Settings", (x) =>
{
// create a new instance of the flyout
SettingsFlyout settings = new SettingsFlyout();
// set the desired width. If you leave this out, you will get Narrow (346px)
// optionally change header and content background colors away from defaults (recommended)
// if using Callisto's AppManifestHelper you can grab the element from some member var you held it in
// settings.HeaderBrush = new SolidColorBrush(App.VisualElements.BackgroundColor);
settings.HeaderBrush = new SolidColorBrush(Colors.Black);
settings.HeaderText = string.Format("Color Settings", App.VisualElements.DisplayName);
settings.Background = new SolidColorBrush(_background);
settings.Margin = new Thickness(0);
// provide some logo (preferrably the smallogo the app uses)
BitmapImage bmp = new BitmapImage(App.VisualElements.SmallLogoUri);
settings.SmallLogoImageSource = bmp;
// set the content for the flyout
settings.Content = new ColorSettings();
settings.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Stretch;
// open it
settings.IsOpen = true;
// this is only for the test app and not needed
// you would not use this code in your real app
// ObjectTracker.Track(settings);
});
Currently using (SettingsPane.Show()) i can be able to show the added flyout items list but I want to programmatically open any setting Flyout item instead of opening a flyout list.
Create a new class
public class SettingsFlyout
{
private const int _width = 346;
private Popup _popup;
/// <summary>
/// Show the Flyout with the UserControl as content
/// </summary>
/// <param name="control"></param>
public void ShowFlyout(UserControl control)
{
_popup = new Popup();
_popup.Closed += OnPopupClosed;
Window.Current.Activated += OnWindowActivated;
_popup.IsLightDismissEnabled = true;
_popup.Width = _width;
_popup.Height = Window.Current.Bounds.Height;
control.Width = _width;
control.Height = Window.Current.Bounds.Height;
_popup.Child = control;
_popup.SetValue(Canvas.LeftProperty, Window.Current.Bounds.Width - _width);
_popup.SetValue(Canvas.TopProperty, 0);
_popup.IsOpen = true;
}
private void OnWindowActivated(object sender, Windows.UI.Core.WindowActivatedEventArgs e)
{
if (e.WindowActivationState == Windows.UI.Core.CoreWindowActivationState.Deactivated)
{
_popup.IsOpen = false;
}
}
void OnPopupClosed(object sender, object e)
{
Window.Current.Activated -= OnWindowActivated;
}
}
In a XAML page take a button and then write the button click event.
private void Button_Click_1(object sender, RoutedEventArgs e)
{
SettingsFlyout flyout = new SettingsFlyout();
flyout.ShowFlyout(new FlyoutContentUserControl());
}
Please note one thing FlyoutContentUserControl is the user control which you would like to show.
Credits goes to Q42.WinRT
The code you posted registers a SettingsCommands to the system settings pane. When your command is invoked from the system settings pane, you new up a SettingsFlyout instance and set IsOpen=True on it.
You just need to refactor this code to a separate method (e.g. ShowColorSettingsFlyout()), and also call that method from your Button.Click event handler. You can create a new Callisto SettingsFlyout and set IsOpen=True on it anywhere.
In App.xaml.cs add the following to register your SettingsFlyout e.g. CustomSetting ...
protected override void OnWindowCreated(WindowCreatedEventArgs args)
{
SettingsPane.GetForCurrentView().CommandsRequested += OnCommandsRequested;
}
private void OnCommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
{
args.Request.ApplicationCommands.Add(new SettingsCommand(
"Custom Setting", "Custom Setting", (handler) => ShowCustomSettingFlyout()));
}
public void ShowCustomSettingFlyout()
{
CustomSetting CustomSettingFlyout = new CustomSetting();
CustomSettingFlyout.Show();
}
Then anywhere in your code you want to programmatically open the CustomSetting flyout, call ShowCustomSettingFlyout, e.g. in the event handler for a button click...
void Button_Click_1(object sender, RoutedEventArgs e)
{
ShowCustomSettingFlyout()
}
Adapted from: Quickstart: Add app settings (XAML).