I'm developing a Windows Phone 7 app with C#.
I'm trying to do a login with Facebook Login Page.
Here is my cs source:
namespace FacebookLogin
{
public partial class MainPage : PhoneApplicationPage
{
private const string appId = "xxx";
private const string apiKey = "xxx"; //insert your apps key here... see developers.facebook.com/setup/
private readonly string[] extendedPermissions = new[] { "user_about_me" };
private bool loggedIn = false;
private FacebookClient fbClient;
PhoneApplicationService appService = PhoneApplicationService.Current;
// Constructor
public MainPage()
{
InitializeComponent();
fbClient = new FacebookClient();
FacebookLoginBrowser.Loaded += new RoutedEventHandler(FacebookLoginBrowser_Loaded);
//FacebookLoginBrowser.Navigated +=new EventHandler<System.Windows.Navigation.NavigationEventArgs>(FacebookLoginBrowser_Navigated);
}
private void FacebookLoginBrowser_Loaded(object sender, RoutedEventArgs e)
{
if (!loggedIn)
{
LoginToFacebook();
}
}
private void FacebookLoginBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookOAuthResult oauthResult;
if (FacebookOAuthResult.TryParse(e.Uri, out oauthResult))
{
if (oauthResult.IsSuccess)
{
fbClient = new FacebookClient(oauthResult.AccessToken);
loggedIn = true;
loginSucceeded();
}
else
{
MessageBox.Show(oauthResult.ErrorDescription);
}
}
}
private void LoginToFacebook()
{
TitlePanel.Visibility = Visibility.Visible;
FacebookLoginBrowser.Visibility = Visibility.Visible;
InfoPanel.Visibility = Visibility.Collapsed;
var loginParameters = new Dictionary<string, object>
{
{ "response_type", "token" }
// { "display", "touch" } // by default for wp7 builds only (in Facebook.dll), display is set to touch.
};
var navigateUrl = FacebookOAuthClient.GetLoginUrl(appId, null, extendedPermissions, loginParameters);
FacebookLoginBrowser.Navigate(navigateUrl);
}
// At this point we have an access token so we can get information from facebook
private void loginSucceeded()
{
TitlePanel.Visibility = Visibility.Visible;
FacebookLoginBrowser.Visibility = Visibility.Collapsed;
InfoPanel.Visibility = Visibility.Visible;
fbClient.GetCompleted +=
(o, e) =>
{
if (e.Error == null)
{
var result = (IDictionary<string, object>)e.GetResultData();
Dispatcher.BeginInvoke(() => MyData.ItemsSource = result);
}
else
{
MessageBox.Show(e.Error.Message);
}
};
fbClient.GetAsync("/me");
}
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs args)
{
appService.State["fbClient"] = fbClient;
base.OnNavigatedFrom(args);
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs args)
{
base.OnNavigatedTo(args);
}
}
}
And here is my XAML code:
<phone:PhoneApplicationPage
x:Class="FacebookLogin.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28" Visibility="Collapsed">
<TextBlock x:Name="ApplicationTitle" Text="MI APLICACIÓN" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="nombre de la página" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<phone:WebBrowser HorizontalAlignment="Left" Name="FacebookLoginBrowser" Height="607" VerticalAlignment="Top" Width="450" />
<Grid x:Name="InfoPanel" Grid.Row="1">
<ListBox x:Name="MyData" Height="657" HorizontalAlignment="Stretch" VerticalAlignment="Top">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Stretch" MinWidth="500">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding Key}"/>
<TextBlock Grid.Column="1" Text="{Binding Value}" TextWrapping="Wrap"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Grid>
</Grid>
<!--<phone:PhoneApplicationPage.ApplicationBar>
<shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
<shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Botón 1"/>
<shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="Botón 2"/>
<shell:ApplicationBar.MenuItems>
<shell:ApplicationBarMenuItem Text="Elemento de menú 1"/>
<shell:ApplicationBarMenuItem Text="Elemento de menú 2"/>
</shell:ApplicationBar.MenuItems>
</shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>-->
</phone:PhoneApplicationPage>
Where is the error? FacebookLoginBrowser_Navigated isn't never reached.
Here's the answer (and I knew it before even looking at your code, but I did doublecheck). The WP7 Browser control defaults to having JavaScript disabled (why they did that is beyond me). SO, you need to set the "IsScriptEnabled" property of the web browser control to True (you can do this in code or in XAML), and then I bet everything will work.
You have your FacebookLoginBrowser_Navigated event handler commented out. That is the correct one to use. Not a RoutedEventHandler just an EventHandler.
Also it might not be a bad idea just to set the eventhandler in design view on the browser control if it's not absolutely necessary to dynamically create the event.
Related
hi i need to how can i make a overlay like page in xaml for windows phone ? Like, if i tap a button it will show a overlay like message loading... and then actually start to work. All i have been able to create a popup in xaml.
<Popup x:Name="myPopup" HorizontalAlignment="Center" VerticalAlignment="Center" >
<Grid >
<Grid.RowDefinitions>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock FontSize="25" Grid.Column="1" Margin="20" Text="loading"/>
</Grid>
</Popup>
Can you plz tell me how can make overlay like message ?
If you need and overlay there it is.
First you need an usercontrol.
<UserControl x:Class="ABC.Test.OverLay"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
d:DesignHeight="800" d:DesignWidth="480">
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="400"/>
<RowDefinition Height="400"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="1">
<ProgressBar IsIndeterminate="True" Foreground="Red" Height="80" Width="480" VerticalAlignment="Center"/>
<TextBlock Text="loading" Foreground="Red" HorizontalAlignment="Center" FontSize="20"/>
</StackPanel>
</Grid>
In Codebehind :
public OverLay()
{
InitializeComponent();
this.LayoutRoot.Height = Application.Current.Host.Content.ActualHeight;
this.LayoutRoot.Width = Application.Current.Host.Content.ActualWidth;
SystemTray.IsVisible = false;
}
In the page where you would show the overlay, create an instance of popup just like this:
private Popup popup;
Initialize it after InitializeComponent(),like this :
this.popup = new Popup();
on the event where you need the overlay to show up, try like this :
this.LayoutRoot.Opacity = 0.2;
OverLay _ovr = new OverLay();
this.popup.Child = _ovr;
this.popup.IsOpen = true;
BackgroundWorker _worker = new BackgroundWorker();
_worker.DoWork += (s, a) =>
{
//you can do your work here.
Thread.Sleep(3000);
};
_worker.RunWorkerCompleted += (s, a) =>
{
popup.IsOpen = false;
this.LayoutRoot.Opacity = 1.0;
};
_worker.RunWorkerAsync();
Find the working Here on Nokia Developers community
So I am just starting out with this stuff and have run into some strife. There was a pivot soundboard application that I needed to change into a series of panorama pages but have the same functionality.
I have finished all the xaml and c# appropriately but I think because I had to create a new MainPage and delete the older one I have created several errors. I suspect they all have a similar cause so I will just provide three.
Error 1 The type 'SoundBoard.MainPage' already contains a definition
for 'LayoutRoot' \SoundBoard\obj\Debug\Cartoons.g.cs
Error 30 The name 'AudioPlayer' does not exist in the current
context \SoundBoard\Cartoons.xaml.cs
Error 7 Type 'SoundBoard.MainPage' already defines a member called
'InitializeComponent' with the same parameter types
\SoundBoard\obj\Debug\Cartoons.g.cs
I'll link my current MainPage and Cartoons and hopefully you guys can help me out.
MainPage.xaml:
<phone:PhoneApplicationPage
x:Class="SoundBoard.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DataContext="{d:DesignData SampleData/SampleData.xaml}"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel Grid.Row="0" Margin="12,17,0,28">
<TextBlock Text="SoundBoard" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock Text="Categories" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button Content="Warnings" HorizontalAlignment="Left" Margin="244,304,0,0" VerticalAlignment="Top" Height="160" Width="182" Background="Red" Click="Button_Click_3"/>
<Button Content="Taunts" HorizontalAlignment="Left" Margin="27,304,0,0" VerticalAlignment="Top" Height="160" Width="182" Background="Red" Click="Button_Click_2"/>
<Button Content="Cartoons" HorizontalAlignment="Left" Margin="244,123,0,0" VerticalAlignment="Top" Height="160" Width="182" Background="Red" Click="Button_Click_1"/>
<Button Content="Animals" HorizontalAlignment="Left" Margin="27,123,0,0" VerticalAlignment="Top" Height="160" Width="182" Background="Red" Click="Button_Click"/>
</Grid>
</Grid>
</phone:PhoneApplicationPage>
MainPage.xaml.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
namespace SoundBoard
{
public partial class FirstPage : PhoneApplicationPage
{
public FirstPage()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/Animals.xaml", UriKind.Relative));
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/Cartoons.xaml", UriKind.Relative));
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/Taunts.xaml", UriKind.Relative));
}
private void Button_Click_3(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/Warnings.xaml", UriKind.Relative));
}
}
}
Cartoons.xaml:
<phone:PhoneApplicationPage
x:Class="SoundBoard.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DataContext="{d:DesignData SampleData/SampleData.xaml}"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot contains the root grid where all other page content is placed-->
<Grid x:Name="LayoutRoot">
<phone:Panorama Title="{Binding Path=LocalizedResources.ApplicationTitle,
Source={StaticResource LocalizedStrings}}">
<!--Panorama item one-->
<phone:PanoramaItem Header="Cartoons">
<Grid>
<Image HorizontalAlignment="Center" Height="431" Margin="10,10,0,0" VerticalAlignment="Top" Width="400" Source="/Assets/cartoon.jpg"/>
</Grid>
</phone:PanoramaItem>
<!--Panorama item two-->
<phone:PanoramaItem Header="Sounds">
<phone:LongListSelector
Margin="0,0,-12,0"
ItemsSource="{Binding Cartoons.Items}"
LayoutMode="Grid"
GridCellSize="150,150"
>
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<Grid Background="{StaticResource PhoneAccentBrush}">
<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>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
</phone:PanoramaItem>
<!--Panorama item three-->
<phone:PanoramaItem Header="Record">
<Grid>
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<MediaElement x:Name="AudioPlayer" AutoPlay="False" />
<StackPanel>
<ToggleButton Content="Record"
Checked="RecordAudioChecked"
Unchecked="RecordAudioUnchecked"/>
<Grid Width="200"
Height="200"
Name="ReelGrid"
RenderTransformOrigin=".5,.5">
<Grid.RenderTransform>
<CompositeTransform />
</Grid.RenderTransform>
<Ellipse Fill="{StaticResource PhoneAccentBrush}" />
<Ellipse Height="20"
Width="20"
Fill="{StaticResource PhoneForegroundBrush}" />
<Rectangle Height="20"
Width="20"
Margin="0,20,0,20"
VerticalAlignment="Top"
Fill="{StaticResource PhoneForegroundBrush}" />
<Rectangle Height="20"
Width="20"
Margin="0,20,0,20"
VerticalAlignment="Bottom"
Fill="{StaticResource PhoneForegroundBrush}" />
<Rectangle Height="20"
Width="20"
Margin="0,0,20,0"
HorizontalAlignment="Right"
Fill="{StaticResource PhoneForegroundBrush}" />
<Rectangle Height="20"
Width="20"
Margin="20,0,0,0"
HorizontalAlignment="Left"
Fill="{StaticResource PhoneForegroundBrush}" />
</Grid>
<Button Name="PlayAudio" Content="Play" Click="PlayAudioClick" />
</StackPanel>
</Grid>
</Grid>
</phone:PanoramaItem>
</phone:Panorama>
</Grid>
</phone:PhoneApplicationPage>
Cartoons.xaml.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using SoundBoard.Resources;
using Coding4Fun.Toolkit.Audio;
using Coding4Fun.Toolkit.Audio.Helpers;
using System.IO;
using System.IO.IsolatedStorage;
using Coding4Fun.Toolkit.Controls;
using SoundBoard.ViewModels;
using Newtonsoft.Json;
namespace SoundBoard
{
public partial class Cartoons : PhoneApplicationPage
{
private MicrophoneRecorder _recorder = new MicrophoneRecorder();
private IsolatedStorageFileStream _audioStream;
private string _tempFileName = "tempWav.wav";
public Cartoons()
{
InitializeComponent();
DataContext = App.ViewModel;
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;
if (File.Exists(data.FilePath))
{
AudioPlayer.Source = new Uri(data.FilePath, UriKind.RelativeOrAbsolute);
}
else
{
using (var storageFolder = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var stream = new IsolatedStorageFileStream(data.FilePath, FileMode.Open, storageFolder))
{
AudioPlayer.SetSource(stream);
}
}
}
selector.SelectedItem = null;
}
private void BuildLocalizedApplicationBar()
{
ApplicationBar = new ApplicationBar();
ApplicationBarIconButton recordAudioAppBar =
new ApplicationBarIconButton();
recordAudioAppBar.IconUri = new Uri("/Assets/AppBar/Save.png", UriKind.Relative);
recordAudioAppBar.Text = AppResources.AppBarSave;
recordAudioAppBar.Click += recordAudioAppBar_Click;
ApplicationBar.Buttons.Add(recordAudioAppBar);
ApplicationBar.IsVisible = false;
}
void recordAudioAppBar_Click(object sender, EventArgs e)
{
InputPrompt fileName = new InputPrompt();
fileName.Message = "What should we call the sound?";
fileName.Completed += FileNameCompleted;
fileName.Show();
}
private void FileNameCompleted(object sender, PopUpEventArgs<string, PopUpResult> e)
{
if (e.PopUpResult == PopUpResult.Ok)
{
// Create a sound data object
SoundData soundData = new SoundData();
soundData.FilePath = string.Format("/customAudio/{0}.wav", DateTime.Now.ToFileTime());
soundData.Title = e.Result;
// Save the wav file into the DIR /customAudio/
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication()) {
if (!isoStore.DirectoryExists("/customAudio/"))
isoStore.CreateDirectory("/customAudio/");
isoStore.MoveFile(_tempFileName, soundData.FilePath);
}
// Add the SoundData to App.ViewModel.CustomSounds
App.ViewModel.CustomSounds.Items.Add(soundData);
// Save the list of CustomSounds to isolatedStorage.ApplicationSettings
var data = JsonConvert.SerializeObject(App.ViewModel.CustomSounds);
IsolatedStorageSettings.ApplicationSettings[SoundModel.CustomSoundKey] = data;
IsolatedStorageSettings.ApplicationSettings.Save();
// We'll need to modify sound model to retrieve CustomSounds
//from isolatedStorage.ApplicationSettings
NavigationService.Navigate(new Uri("", UriKind.RelativeOrAbsolute));
}
}
private void RecordAudioChecked(object sender, RoutedEventArgs e)
{
PlayAudio.IsEnabled = false;
ApplicationBar.IsVisible = false;
RotateCirlce.Begin();
_recorder.Start();
}
private void RecordAudioUnchecked(object sender, RoutedEventArgs e)
{
_recorder.Stop();
SaveTempAudio(_recorder.Buffer);
PlayAudio.IsEnabled = true;
ApplicationBar.IsVisible = true;
RotateCircle.Stop();
}
private void SaveTempAudio(MemoryStream buffer)
{
//defensive...
if (buffer == null)
throw new ArgumentNullException("Attempting a save on empty sound buffer.");
//Clean out hold on audioStream
if (_audioStream != null)
{
AudioPlayer.Stop();
AudioPlayer.Source = null;
_audioStream.Dispose();
}
var bytes = buffer.GetWavAsByteArray(_recorder.SampleRate);
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication()) {
if (isoStore.FileExists(_tempFileName))
isoStore.DeleteFile(_tempFileName);
_tempFileName = string.Format("{0}.wav", DateTime.Now.ToFileTime());
_audioStream = isoStore.CreateFile(_tempFileName);
_audioStream.Write(bytes, 0, bytes.Length);
//Play ... SetSource of a mediaElement
AudioPlayer.SetSource(_audioStream);
}
}
private void PlayAudioClick(object sender, RoutedEventArgs e)
{
AudioPlayer.Play();
}
}
}
As I said it is probably something dumb but I am really stuck so would really appreciate any advice.
Thanks in advance.
It seems that all the problems reside in auto-generated files Cartoons.g.cs. The only error that points to non fully auto-generated file is this :
The name 'AudioPlayer' does not exist in the current context \SoundBoard\Cartoons.xaml.cs
Which complaining about AudioPlayer doesn't exists when it does exist, declared in Cartoons.xaml. So that's all weird errors.
First thing I will do is clean up (from visual studio, or manually delete bin and debug folders) and rebuild the project, and or even restart Visual Studio. Those steps can fix weird errors most of the time.
The problem is that both Cartoons.xaml and MainPage.xaml have the same line x:Class="SoundBoard.MainPage". I'm not sure but think that Cartoons.xaml should have different value for x:Class attribute
When I run my app in windows phone 8 emulator, I am getting this Exception thrown after which I can't run my app.
MainPage.xaml
<phone:PhoneApplicationPage
x:Class="LightBrowser.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="PortraitOrLandscape" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock Text="Light Browser" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button x:Name="Go" Content="Go" HorizontalAlignment="Right" Margin="0,27,0,0" VerticalAlignment="Top" Click="Button_Click_1" Width="79"/>
<phone:WebBrowser x:Name="Light_Browser" Margin="0,99,0,0"/>
<Button x:Name="Back" Content="Back" HorizontalAlignment="Right" Margin="343,-24,0,0" VerticalAlignment="Top" Height="65" Click="Back_Click"/>
<Button x:Name="Refresh" Content="Refresh" Margin="170,-24,159,0" VerticalAlignment="Top" Height="65" Click="Back_Click" HorizontalAlignment="Center"/>
<TextBox x:Name="URL" Margin="0,27,68,0" VerticalAlignment="Top" Grid.Row="1" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" TextOptions.TextHintingMode="Animated" AcceptsReturn="True" Text="http://www.google.co.in/"/>
<Button x:Name="Home" Content="Home" HorizontalAlignment="Left" Margin="3,-23,0,0" VerticalAlignment="Top" Click="Home_Click" Height="67" Width="110"/>
</Grid>
</Grid>
</phone:PhoneApplicationPage>
MainPage.xaml.cs
namespace LightBrowser
{
public partial class MainPage : PhoneApplicationPage
{
private Stack<Uri> _history = new Stack<Uri>();
private string home = "http://www.google.co.in/";
private Uri _current = null;
// Constructor
public MainPage()
{
InitializeComponent();
Light_Browser.Navigate(new Uri("http://www.google.co.in/", UriKind.Absolute));
Light_Browser.IsScriptEnabled = true;
}
private void Button_Click_1(object sender, NavigatingEventArgs e)
{
Uri url = e.Uri;
URL.Text = url.ToString();
string site = URL.Text;
Light_Browser.Navigate(new Uri(site, UriKind.Absolute));
}
private void Home_Click(object sender, NavigatingEventArgs e)
{
Light_Browser.Navigate(new Uri(home, UriKind.Absolute));
Uri url = e.Uri;
URL.Text = url.ToString();
}
private void Back_Click(object sender, NavigatingEventArgs e)
{
Light_Browser.GoBack();
Uri url = e.Uri;
URL.Text = url.ToString();
}
private void Refresh_Click(object sender, NavigatingEventArgs e)
{
Uri url = e.Uri;
URL.Text = url.ToString();
string site=URL.Text;
Light_Browser.Navigate(new Uri(site, UriKind.RelativeOrAbsolute));
}
private void Browser_NavigationFailed(object sender, System.Windows.Navigation.NavigationFailedEventArgs e)
{
MessageBox.Show("Navigation to this page failed, check your internet connection");
}
private async void Browser_Navigated(object sender, NavigationEventArgs e)
{
// If we navigated back, pop the last entry
if (_history.Count > 0 && _history.Peek() == e.Uri)
{
_history.Pop();
}
// Otherwise, if this isn't the first navigation, push the current
else if (_current != null)
{
_history.Push(_current);
}
// The current page is now the one we've navigated to
_current = e.Uri;
}
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e) {
base.OnBackKeyPress(e);
if (_history.Count == 0)
{
// No history, allow the back button
// Or do whatever you need to do, like navigate the application page
return;
}
// Otherwise, if this isn't the first navigation, push the current
else
Light_Browser.GoBack();
}
}
}
XamlParseException Occured
A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in System.Windows.ni.dll
And this error points to InitializeComponent();
Is there a way to customize button on WPF MessageBox instead "Yes" and "No", I want "Enter" or "Exit" or something like that . All web i search told it is difficult do it rather by creating a window and all but those were 3 or 4 year old answers. Right now is there any easy way to do it ?
You can customize WPF Toolkit Extende MessageBox. Or you can use a custom one WPFCustomMessageBox that ACB suggested.
I know this is a late answer but it can be useful.
I needed the same thing and I found this way and I wanted to share it.
I use a window for this.
In my window, I have a label for the caption and another for the message.
And three buttons (or more if needed).
Here is my window :
<Window x:Class="CapronCAD.LIB.Controls.CapronMessageBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:CapronCAD.LIB.Controls"
mc:Ignorable="d" Height="450" Width="800" WindowStyle="None" WindowStartupLocation="CenterOwner" WindowState="Minimized" ResizeMode="NoResize" ShowInTaskbar="False" AllowsTransparency="True" Background="Transparent">
<Grid x:Name="grdMessageBox" Background="#33000B4B">
<Border BorderBrush="Black" BorderThickness="0" HorizontalAlignment="Center" Height="250" Margin="0" VerticalAlignment="Center" Width="600" Background="White" CornerRadius="5">
<Grid>
<Button x:Name="btnMessageBoxYes" FontWeight="SemiBold" Content="Oui" HorizontalAlignment="Right" VerticalAlignment="Bottom" Style="{DynamicResource ResourceKey=Capron_Violet_ButtonStyle}" Margin="0,0,30,30" Width="60" Click="btnMessageBoxYes_Click"/>
<Button x:Name="btnMessageBoxNo" FontWeight="SemiBold" Content="Non" HorizontalAlignment="Right" VerticalAlignment="Bottom" Style="{DynamicResource ResourceKey=Capron_Violet_ButtonStyle}" Margin="0,0,103,30" Width="60" Background="#FFCFC9FF" Foreground="#FF6F5DF5" Click="btnMessageBoxNo_Click"/>
<TextBlock x:Name="tbMessageBoxCaption" FontWeight="SemiBold" Margin="30,43,10,0" TextWrapping="Wrap" Text="-" VerticalAlignment="Top" FontFamily="Poppins" FontSize="14"/>
<TextBlock x:Name="tbMessageBoxMessage" Margin="30,80,10,0" TextWrapping="Wrap" Text="-" VerticalAlignment="Top" FontFamily="Poppins"/>
<Image x:Name="imgMessageBoxCancel" HorizontalAlignment="Right" Height="18" Margin="0,19,30,0" VerticalAlignment="Top" Width="18" Source="/CapronCAD.LIB;component/Resources/CloseBlack.png" MouseLeftButtonUp="imgMessageBoxCancel_MouseLeftButtonUp"/>
<Button x:Name="btnMessageBoxClose" FontWeight="SemiBold" Content="Fermer" HorizontalAlignment="Center" VerticalAlignment="Bottom" Style="{DynamicResource ResourceKey=Capron_Violet_ButtonStyle}" Margin="0,0,0,30" Visibility="Collapsed" Click="btnMessageBoxClose_Click"/>
</Grid>
</Border>
</Grid>
Here is the simple method which shows the window as a dialog :
internal static System.Windows.Forms.DialogResult ShowCustomMessageBox(string message, string caption = "Default caption", bool dialog = true)
{
Controls.CapronMessageBox mb = new Controls.CapronMessageBox(caption, message, dialog);
mb.Topmost = true;
mb.WindowState = WindowState.Maximized;
mb.ShowDialog();
if (mb.DialogResult == null)
return System.Windows.Forms.DialogResult.None;
else if (mb.DialogResult == true)
return System.Windows.Forms.DialogResult.Yes;
else
return System.Windows.Forms.DialogResult.No;
}
Here is the code behind the window :
public partial class CapronMessageBox: Window
{
public CapronMessageBox(string caption, string message, bool dialog)
{
InitializeComponent();
tbMessageBoxCaption.Text = caption;
tbMessageBoxMessage.Text = message;
if (!dialog)
{
btnMessageBoxClose.Visibility = Visibility.Visible;
btnMessageBoxNo.Visibility = Visibility.Collapsed;
btnMessageBoxYes.Visibility = Visibility.Collapsed;
}
}
private void btnMessageBoxNo_Click(object sender, RoutedEventArgs e)
{
DialogResult = false;
}
private void imgMessageBoxCancel_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
this.Close();
}
private void btnMessageBoxYes_Click(object sender, RoutedEventArgs e)
{
DialogResult = true;
}
private void btnMessageBoxClose_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
And here how I call it :
if (UserMethods.ShowCustomMessageBox("Do you want to save changes?", "Are you sure?", false) == DialogResult.Yes)
{
btnSave_Click(btnSave, null);
}
And here is how it seems :
My problem is first I'm downladin xml file from server like this:
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
//pobieranie danych z pliku xml znajdujacego sie na serwerze
WebClient client = new WebClient();
client.DownloadStringCompleted += HttpsCompleted;
client.DownloadStringAsync(new Uri("Myurl/baza.xml"));
}
private void HttpsCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
XDocument xdoc3 = XDocument.Parse(e.Result, LoadOptions.None);
var data = from query in xdoc3.Descendants("Item")
select new Item
{
name = (string)query.Element("name"),
prise = (int)query.Element("prise"),
howmany = (int)query.Element("howmany")
};
items_listBox.ItemsSource = data;
status_textBlock.Text = "Data ok";
}
else {
status_textBlock.Text = "Fail";
kup_button.Visibility = 0;
}
Then i'v made a refresh button, and add function to it, basicly the same code:
private void button1_Click(object sendera, RoutedEventArgs a)
{
WebClient client2 = new WebClient();
client2.DownloadStringCompleted += HttpsCompleteda;
client2.DownloadStringAsync(new Uri(Myurl/baza.xml"));
}
private void HttpsCompleteda(object sendera, DownloadStringCompletedEventArgs a)
{
#region server_ok
if (a.Error == null
{
#region refresh
XDocument xdoca = XDocument.Parse(a.Result, LoadOptions.None);
var new_data = from query in xdoca.Descendants("Item")
select new Item
{
name = (string)query.Element("name"),
prise = (int)query.Element("prise"),
howmany = (int)query.Element("howmany")
};
items_listBox.ItemsSource = new_data;
}
After laod first xml, it (xml file) is chenged(i can see via my web browser) but when i refresh it looks steel the same in
items_listBox.ItemsSource
any ideas? thanks for help
xaml code
x:Class="Sklep.Page1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
mc:Ignorable="d" d:DesignHeight="768" d:DesignWidth="480"
shell:SystemTray.IsVisible="True" Loaded="PhoneApplicationPage_Loaded">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="Sklep" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="Sklep" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}" Height="49" Width="456" FontSize="30" />
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button Content="zamow" Height="70" HorizontalAlignment="Left" Margin="-12,474,0,0" Name="kup_button" VerticalAlignment="Top" Width="480" Click="kup_button_Click" />
<TextBlock HorizontalAlignment="Left" Margin="230,550,0,74" Name="textBlock1" Text="Ilość sztuk" Width="190" />
<TextBox Height="57" HorizontalAlignment="Left" Margin="0,536,0,0" Name="order_textBox" Text="1" VerticalAlignment="Top" Width="224" TextAlignment="Right" FontSize="18" />
<CheckBox Content="zapłacone" Height="86" HorizontalAlignment="Left" Margin="171,568,0,0" Name="pay_box" VerticalAlignment="Top" Width="261" />
<ListBox x:Name="items_listBox" MinHeight="200" MinWidth="300" Margin="6,62,6,174" MaxHeight="500">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="10" >
<TextBlock Text="{Binding name}"/>
<TextBlock Text="{Binding prise}"/>
<TextBlock Text="{Binding howmany}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<TextBlock Height="53" HorizontalAlignment="Left" Margin="1,3,0,0" Name="status_textBlock" Text="" VerticalAlignment="Top" Width="449" TextAlignment="Center" />
<Button Content="Odswież" Height="103" HorizontalAlignment="Left" Margin="339,545,0,0" Name="button1" VerticalAlignment="Top" Width="114" FontSize="15" Click="button1_Click" />
</Grid>
</Grid>
The request will be cached by the WebClient.
The easiest solution is to make the request look like a different one by adding something unique to the query string.
client.DownloadStringAsync(new Uri("Myurl/baza.xml?rand=" + Guid.NewGuid()));
Your problem seems more to be a data binding problem than about a web service call. You should give your XAML code.
I've solved it using
static public WebClient public_webclient